JS中判断元素是否为数组有几种方法,具体怎样做
Admin 2022-06-14 群英技术资讯 542 次浏览
此处提供可供验证的数据类型
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
总结
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
本文实例为大家分享了JavaScript实现简单音乐播放器的具体代码,供大家参考,具体内容如下主要功能:快进、快退、暂停、上下一首、禁音、鼠标控制音量、自动下一首、显示歌名htmlhead @*不提供音频*@ meta name=viewport content=width=device-width /
本篇文章给大家带来了关于javascript的相关知识,主要介绍了JavaScript事件循环同步任务与异步任务,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下。
这篇文章主要介绍了React Fiber的工作原理的相关资料,帮助大家更好的理解和学习使用React框架,感兴趣的朋友可以了解下
图像优化对于网站建设和优化来说,是很重要的一部分,能大大提高网站的性能。对此,本文就给大家来分享一下JPEG/JPG、PNG、WebP这些常见的图片怎样优化,这些图像的应用场景及优缺点?
本文主要介绍了如何在Vue中动态添加类名,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008