typeof 和 instanceof

2019-06-22  本文已影响0人  Ace__丨
typeof可能会返回如下的值:

1."undefined",
2."boolean",
3."string",
4."number",
5."object",
6."function"

let u;
console.log(typeof(u)); //"undefined"

let n = null;
console.log(typeof(n)); //"object"    null表示一个空对象指针,所以使用typeof返回"object"

let b = true;
console.log(typeof(b)); //"boolean"

let s = "hello";
console.log(typeof(s)); //"string"

let n = 123;
console.log(typeof(s)); //"number"

let nan = NAN;
console.log(typeof(nan)); //"number"

let obj = new Object();
console.log(typeof(obj)); //"object"

let arr = [];
console.log(typeof(arr)); //"object"

let f = function(){};
console.log(typeof f); //"function"
typeof是检测一个变量是不是基本数据类型的最佳工具,但在检测引用类型值的时候,我们会使用instanceof

所有引用类型的值都是Object的实例,在检测引用类型和Object构造函数时,instanceof都会返回true,当检测基本类型时,都会返回false

function Person() {};
let person = new Person();
console.log(person instanceof Object);//true
console.log(person instanceof Person);//true

let arr = [];
console.log(arr instanceof Array);//true

总结:确定一个值是那种基本类型可以使用typeof,而确定一个值是哪种引用类型可以使用instanceof

上一篇下一篇

猜你喜欢

热点阅读