源地址https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof
typeof操作符
1 // Numbers 2 typeof 37 === 'number'; 3 typeof 3.14 === 'number'; 4 typeof Math.LN2 === 'number'; 5 typeof Infinity === 'number'; 6 typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写 7 typeof Number(1) === 'number'; // 但不要使用这种形式! 8 9 // Strings 10 typeof "" === 'string'; 11 typeof "bla" === 'string'; 12 typeof (typeof 1) === 'string'; // typeof总是返回一个字符串 13 typeof String("abc") === 'string'; // 但不要使用这种形式! 14 15 // Booleans 16 typeof true === 'boolean'; 17 typeof false === 'boolean'; 18 typeof Boolean(true) === 'boolean'; // 但不要使用这种形式! 19 20 // Symbols 21 typeof Symbol() === 'symbol'; 22 typeof Symbol('foo') === 'symbol'; 23 typeof Symbol.iterator === 'symbol'; 24 25 // Undefined 26 typeof undefined === 'undefined'; 27 typeof declaredButUndefinedVariable === 'undefined'; 28 typeof undeclaredVariable === 'undefined'; 29 30 // Objects 31 typeof {a:1} === 'object'; 32 33 // 使用Array.isArray 或者 Object.prototype.toString.call 34 // 区分数组,普通对象 35 typeof [1, 2, 4] === 'object'; 36 37 typeof new Date() === 'object';
Array.isArray()判断是否为数组
1 var ar = []; 2 var result = Array.isArray(ar); 3 // Output: true 4 5 var ar = new Array(); 6 var result = Array.isArray(ar); 7 // Output: true 8 9 var ar = [1, 2, 3]; 10 var result = Array.isArray(ar); 11 // Output: true 12 13 var result = Array.isArray("an array"); 14 document.write(result); 15 // Output: false
Object.prototype.toString.call()精准判断数据类型
1 console.log(Object.prototype.toString.call(123)) //[object Number] 2 console.log(Object.prototype.toString.call('123')) //[object String] 3 console.log(Object.prototype.toString.call(undefined)) //[object Undefined] 4 console.log(Object.prototype.toString.call(true)) //[object Boolean] 5 console.log(Object.prototype.toString.call({})) //[object Object] 6 console.log(Object.prototype.toString.call([])) //[object Array] 7 console.log(Object.prototype.toString.call(function(){})) //[object Function]