JavaScript 判断数组的常见方法且比较优缺点

1 使用Array.isArray
Array.isArray([1, 2, 3, 4]); // --> true
Array.isArray({name:‘晓明’}); //–》false
缺点:Array.isArray是ES 5.1推出的,不支持IE6~8,所以在使用的时候需要注意兼容性问题。
2 使用instanceof
instanceof 会判断这个对象的原型链上是否会找到对应的 Array 的原型,找到返回 true,否则返回 false

if([1,2,3,4] instanceof Array){
   console.log('是数组类型');
}else{
   console.log('不是数组类型');
}

缺点:instanceof是判断类型的prototype是否出现在对象的原型链中,但是对象的原型可以随意修改,所以这种判断并不准确。并且也不能判断对象和数组的区别

const obj = {}
obj.__proto__ = Array.prototype
// Object.setPrototypeOf(obj, Array.prototype)
obj instanceof Array // true

[] instanceof Array; // true
[] instanceof Object;//true
3Object.prototype.toString.call()
每一个继承 Object 的对象都有 toString 方法,如果 toString 方法没有重写的话,会返回 [Object type],其中 type 为对象的类型。但当除了 Object 类型的对象外,其他类型直接使用 toString 方法时,会直接返回都是内容的字符串,所以我们需要使用call或者apply方法来改变toString方法的执行上下文。

const an = ['Hello','An'];
an.toString(); // "Hello,An"
Object.prototype.toString.call(an); // "[object Array]"

缺点:不能精准判断自定义对象,对于自定义对象只会返回[object Object]

function f(name) {
  this.name = name;
}
var f1 = new f("martin");
console.log(Object.prototype.toString.call(f1)); //[object Object]

Object.prototype.toString.call(); // 常用于判断浏览器内置对象。

所以综上所述:先使用 Array.isArray判断是否可以判断,如果可以,直接使用isArray进行判断,如果不行,再使用Array.prototype.toString.call进行判断

isArrayFn(value){
	if (typeof Array.isArray === "function") {
	    return Array.isArray(value);
	}else{
	    return Object.prototype.toString.call(value) === "[object Array]";
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值