rt:判断一个变量 arr 是不是数组
function isArray(arr){
//以下方法都可以
//原型链
return arr.__proto__ === Array.prototype;
return Object.getPrototypeOf(arr) === Array.prototype;
return Array.prototype.isPrototypeOf(arr);
//constructor构造函数
return arr.constructor === Array;
//Array.isArray()
return Array.isArray(arr);
//typeof
/*typeof 是一个一元运算,放在一个运算数之前,运算数可以是任意类型。
它返回值是一个字符串,该字符串说明运算数的类型。(typeof 运算符返回一个用来表示表达式的数据类型的字符 串。
运算数为数字 typeof(x) = "number"
字符串 typeof(x) = "string"
布尔值 typeof(x) = "boolean"
对象,数组和null typeof(x) = "object"
函数 typeof(x) = "function")
在 JavaScript 中,判断一个变量的类型尝尝会用 typeof 运算符,在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 “object”。这就需要用到instanceof来检测某个对象是不是另一个对象的实例。
*/
//instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上
return arr instanceof Array //即 arr.constructor.prototype === Array.prototype
//根据对象的class属性(类属性),跨原型链调用toString()方法 Object.prototype.toString.call()
/*
在js中一个对象一旦被创建,在内部会携带创建对象的类型名,一旦创建就不能被修改了。js中提供对象原型中的toString方法去获取该类型名
*/
return Object.prototype.toString.call(arr) === '[object Array]'
}
进阶问题
instanceof在哪些情况下会有问题?为什么?var str = 'str'
console.log(str instanceof String) // false
console.log(typeof str) // string
看上面的例子,str只是一个以string为数据类型的值,但并不属于String对象的实例
var strobj = new String('bbb')
console.log(strobj instanceof String) // true
此时strobj就是String对象的一个实例了。
instanceof运算符只能用于对象,不能用于原始类型的值