数据类型判断的常用方法
以下所有结果,由nodejs执行所得。
1. typeof
The typeof operator returns a string indicating the type of the unevaluated operand.
typeof
返回操作对象的类型(字符串表示)。
语法:
typeof 操作对象
typeof(操作对象)
示例:
let str = new String('abc');
let array = [1,2,3];
console.log(typeof 8);//"number"
console.log(typeof "s");//"string"
console.log(typeof str);//object
console.log(typeof true);//"boolean"
console.log(typeof null);//"object"
console.log(typeof a);//undefined
console.log("==> Array:" + typeof array);//object
上述示例中,typeof null
可参考https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null
特殊值:
console.log(typeof undefined);//"undefined"
console.log(typeof NaN);//"number"
总结:typeof
除了可以判断基本的数据类型外,还可以判断undefined
和NaN
的类型。
2. instanceof
The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.
instanceof
操作符用于检测构造器的prototype属性是否在一个对象的原型链中。从中可以看出,instanceof
无法用于基本数据类型的检测。
示例:
console.log([1,2,3] instanceof Object);//true
console.log(Function instanceof Object);//true
console.log(Array instanceof Object);//true
//null,undefined不在Object原型链中
console.log(undefined instanceof Object);//false
console.log(null instanceof Object);//false
3. null与undefined
null
是一个字面值,表示变量不指向任何对象。
The global undefined property represents the primitive value undefined. It is one of JavaScript's primitive types.
undefined
是原始的数据类型。一个全局的undefined
属性表示原始值undefined
。
undefined
与null
仅字面值相等。
console.log(undefined == null);//true
console.log(undefined === null);//false
undefined
可以使用typeof
来进行判断。undefined
另一种表示方式void 0
console.log(void 0);//undefined
参考文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference