您好,欢迎访问一九零五行业门户网

JS判断是否为数组的6种方式

相关推荐:《javascript视频教程》
一、array.isarray判断
用法:array.isarray(arr)
es5中新增了array.isarray方法,ie8及以下不支持
array.isarray() 用于确定传递的值是否是一个[array], 返回布尔值 true;否则它返回 false。
let arr = [];console.log(array.isarray(arr)); // true
// 下面的函数调用都返回 truearray.isarray([]);array.isarray([1]);array.isarray(new array());array.isarray(new array('a', 'b', 'c', 'd'))// 鲜为人知的事实:其实 array.prototype 也是一个数组。array.isarray(array.prototype);
二、constructor判断用法:arr.constructor === array
object的每个实例都有构造函数 constructor,用于保存着用于创建当前对象的函数
let arr = [];console.log(arr.constructor === array); // true
三、instanceof 判断用法:arr instanceof array
instanceof 主要是用来判断某个实例是否属于某个对象
let arr = [];console.log(arr instanceof array); // true
注:instanceof操作符的问题在于,它假定只有一个全局环境。如果网页中包含多个框架,那实际上就存在两个以上不同的全局执行环境,从而存在两个以上不同版本的array构造函数。如果你从一个框架向另一个框架传入一个数组,那么传入的数组与在第二个框架中原生创建的数组分别具有各自不同的构造函数。(红宝书88页上的原话)
四、原型链上的isprototypeof判断用法:array.prototype.isprototypeof(arr)
array.prototype 属性表示 array 构造函数的原型
isprototypeof()可以用于测试一个对象是否存在于另一个对象的原型链上。
let arr = [];console.log(array.prototype.isprototypeof(arr)); // true

五、object.prototype.tostring用法:object.prototype.tostring.call(arr) === '[object array]'
array继承自object,javascript在array.prototype上重写了tostring,tostring.call(arr)实际上是通过原型链调用了。
let arr = [];console.log(object.prototype.tostring.call(arr) === '[object array]'); // true
六、array 原型链上的 isprototypeof用法:array.prototype.isprototypeof(arr)
array.prototype 属性表示 array 构造函数的原型
let arr = [];console.log(array.prototype.isprototypeof(arr)); // true

顺便复习一下typeof的用法:对于引用类型,不能用typeof来判断,因为返回的都是object
// 基本类型typeof 123; //numbertypeof "abc"; //stringtypeof true; //booleantypeof undefined; //undefinedtypeof null; //objectvar s = symbol;typeof s; //symbol// 引用类型typeof [1,2,3]; //objecttypeof {}; //objecttypeof function(){}; //functiontypeof array; //function array类型的构造函数typeof object; //function object类型的构造函数typeof symbol; //function symbol类型的构造函数typeof number; //function number类型的构造函数typeof string; //function string类型的构造函数typeof boolean; //function boolean类型的构造函数
更多编程相关知识,请访问:编程学习!!
以上就是js判断是否为数组的6种方式的详细内容。
其它类似信息

推荐信息