JS判断元素是否为数组的方式

JS判断元素是否为数组的方式此处提供可供验证的数据类型 leta 1 2 3 4 5 6 letb name 张飞 type tank name 关羽 type soldier name 刘备 type shooter letc 123 letd www lete name 安琪拉 type mage 1 通过 Array isArray Array is

此处提供可供验证的数据类型

 let a = [1,2,3,4,5,6]; let b = [ {name: '张飞', type: 'tank'}, {name: '关羽', type: 'soldier'}, {name: '刘备', type: 'shooter'}, ]; let c = 123; let d = 'www'; let e = {name: '安琪拉', type: 'mage'}; 

1.通过Array.isArray()

Array.isArray()能判断一个元素是否为数组,如果是就返回true,否则就返回false

 console.log(Array.isArray(a)); // true console.log(Array.isArray(b)); // true console.log(Array.isArray(c)); // false console.log(Array.isArray(d)); // false console.log(Array.isArray(e)); // false 

2.通过instanceof判断

instanceof运算符用于检测某个实例是否属于某个对象原型链中

 console.log(a instanceof Array); // true console.log(b instanceof Array); // true console.log(c instanceof Array); // false console.log(d instanceof Array); // false console.log(e instanceof Array); // false 

还可以用于判断对象

console.log(e instanceof Object); // true 

判断是否为数组就是检测Arrray.prototype属性是否存在于变量数组(a,b)的原型链上,显然a,b为数组,拥有Arrray.prototype属性,所以为true

3.通过对象构造函数的constructor判断

console.log(a.constructor === Array); // true console.log(b.constructor === Array); // true 

以下包含判断其它的数据类型验证

console.log(c.constructor === Number); // true console.log(d.constructor === String); // true console.log(e.constructor === Object); // true 

4.通过Object.prototype.toString.call()判断

通过原型链查找调用

console.log(Object.prototype.toString.call(a) === '[object Array]'); // true console.log(Object.prototype.toString.call(b) === '[object Array]'); // true 

以下包含判断其它的数据类型验证

console.log(Object.prototype.toString.call(c) === '[object Number]'); // true console.log(Object.prototype.toString.call(d) === '[object String]'); // true console.log(Object.prototype.toString.call(e) === '[object Object]'); // true 

5.通过对象原型链上的isPrototypeOf()判断

Array.prototype属性为Array的构造函数原型,里面包含有一个方法isPrototypeOf()用于测试一个对象是否存在于另一个对象的原型链上。

 console.log(Array.prototype.isPrototypeOf(a)); // true console.log(Array.prototype.isPrototypeOf(b)); // true console.log(Array.prototype.isPrototypeOf(c)); // false console.log(Array.prototype.isPrototypeOf(d)); // false console.log(Array.prototype.isPrototypeOf(e)); // false 

——为自己整理学习并附上测试代码,欢迎大家采纳及提出意见

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233715.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号