判断数据类型

是否可以使用 typeof bar === 'object' 来检测 bar 是不是 object 类型?

数据类型

最新的 ECMAScript 标准定义了 7 种数据类型:

  • 6 种原始类型:
    • Boolean
    • Null
    • Undefined
    • Number
    • String
    • Symbol( ECMAScript 6 新增 )
  • Object
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof(42) === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number('1') === 'number'; // Number tries to parse things into numbers


// Strings
typeof '' === 'string';
typeof 'bla' === 'string';
typeof `template literal` === 'string';
typeof '1' === 'string'; // note that a number within a string is still typeof string
typeof (typeof 1) === 'string'; // typeof always returns a string
typeof String(1) === 'string'; // String converts anything into a string, safer than toString


// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(1) === 'boolean'; // Boolean will convert values based on if they're truthy or falsy, equivalent to !!


// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'


// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined'; 


// Objects
typeof null === 'object';
typeof {a: 1} === 'object';

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';
typeof /regex/ === 'object'; // See Regular expressions section for historical results


// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';


// Functions
typeof function() {} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';

需要注意的是

typeof null === 'object';

因此,如果想要检测bar是不是object,可以这样子:

    console.log((bar !== null) && (typeof bar ==='object'))
    //如果认为function也是 object,可以用下面的语句
    console.log((bar !== nul)&& (typeof bar ==='object')||(typeof bar ==='function'))

判断是 Array 可以使用instanceof Array, Array.isArray或者 Object.prototype.toString.call

var arr = [];
console.log(arr instanceof  Array );  // 如果数组,返回true

var arr = [];
Array.isArray(arr);

var arr = [];
console.log(Object.prototype.toString.call(arr))  //"[object Array]"

NaN

NaN即Not A Number, typeof NaN 返回Number。

NaN === NaN  //false

判断变量是否是它,不能使用===, 可以使用isNaN方法。

isNaN(bar);
Object.is(bar,NaN); //ES6方法

Object.is()方法,要求严格相等,且 Object.is(NaN,NaN)会返回 true。

你可能感兴趣的:(判断数据类型)