判断变量类型的方法以及null和undefined的区别(面试题)
tyepof与instanceof
当一些复杂的运算得到的变量值,无法直观的看到变量的类型,typeof instantceof此时借助两个方法
1.typeof 用于判断基本的数据结构
2.instanceof 用于判断引用类型
console.log(typeof 10); //numbe
console.log(typeof true); //bollean
console.log(typeof undefined); //undefined
console.log(typeof "10"); //string
console.log(typeof [2,3,4]); //object
console.log(typeof {a:1,b:"5"}) ; //object
console.log(typeof function(){}); //function
console.log(typeof null); //object
//常用在判断条件中
console.log([1,2,3,4,5] instanceof Array); //true
console.log({a:2,b:6} instanceof Object); //true
console.log(function(){} instanceof Function); //true
null和undefined的区别(面试)
null: Null类型,代表“空值”,代表一个空对象指针,使用typeof运算得到 “object”,所以你可以认为它是一个特殊的对象值。
undefined: Undefined类型,当一个声明了一个变量未初始化时,得到的就是undefined。
那到底什么时候是null,什么时候是undefined呢?
1.null表示"没有对象",即该处不应该有值。
2.undefined表示"缺少值",就是此处应该有一个值,但是还没有定义
(1)变量被声明了,但没有赋值时,就等于undefined。
(2)调用函数时,应该提供的参数没有提供,该参数等于undefined。
(3)对象没有赋值的属性,该属性的值为undefined。
(4)函数没有返回值时,默认返回undefined。