此处提供可供验证的数据类型
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判断元素是否为数组的文章就介绍到这了,更多相关JS判断元素为数组内容请搜索站长技术以前的文章或继续浏览下面的相关文章希望大家以后多多支持站长技术!
struts json 类型异常返回到js弹框问题解决办法 当struts 框架配置了异常时 例如...
微软官方博客于 2 月初再次发布提示,将会在 3 月 9 日停止对经典版 Edge 浏览器...
下面是ajax代码和Controller层代码,期初以为是后台程序写错了。 $("#sourcefile...
六、XML展望 任何一项新技术的产生都是有其需求背景的,XML的诞生是在HTML遇到不...
文章目录 关系数据库 关系数据库简介 关系数据结构及形式化定义 关系 关系模式 ...
背景 该问题来自某客户,据描述,他们在部署 MySQL 主从复制时,有时候仅在主库...
前言 我们在使用ajax异步的提交多选框得到需要操作的对象的id,这时我们可以把每...
php实现微信支付 微信支付文档地址: https://pay.weixin.qq.com/wiki/doc/api/i...
本文转载自微信公众号「程序员历小冰」,转载本文请联系程序员历小冰公众号。 疫...
在 2021 年,人们喜欢 Linux 的理由比以往任何时候都多。在这个系列中,我将分享...