JS中判断元素是否为数组有几种方法,具体怎样�

Admin 2022-06-14 群英技术资�

关于“JS中判断元素是否为数组有几种方法,具体怎样做”的知识有一些人不是很理解,对此小编给大家总结了相关内容,具有一定的参考借鉴价值,而且易于学习与理解,希望能对大家有所帮助,有这个方面学习需要的朋友就继续往下看吧�



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

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判断

Obiect的每个实例都有构造函数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

总结


以上就是关于“JS中判断元素是否为数组有几种方法,具体怎样做”的介绍了,感谢各位的阅读,如果大家想要了解更多相关的内容,欢迎关注群英网络,小编每天都会为大家更新不同的知识�

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:[email protected]进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容�

猜你喜欢

群英网络开启智能安全云计算之旅

注册领取新人大礼�
专业资深工程师驻�
7X24小时快速响�
一站式无忧技术支�
免费备案服务

联系我们

24小时售后 24小时售后TEL�0668-2555666 售前咨询TEL�400-678-4567 投诉建议TEL�0668-2555999 投诉建议邮箱:t[email protected] 信息安全TEL�0668-2555118 域名空间客服 公司总机�0668-2555555 公司传真�0668-2555000
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 � 0668-2555555
在线客服
微信公众号
返回顶部
返回顶部 返回顶部