3 个判断数组的方法之间的区别和优劣

本文介绍了JavaScript中的Object.prototype.toString.call()方法原理,以及instanceof用于判断原型链的方法,强调了Array.isArray()在检测数组实例上的优势。同时提到了它们之间的区别和适用场景。
摘要由CSDN通过智能技术生成

1. Object.prototype.toString.call()

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

示例:

console.log(Object.prototype.toString.call("Hello"));//[object String]
console.log(Object.prototype.toString.call(10));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "Lily"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]

function Person(){};
console.log(Object.prototype.toString.call(new Person));//[object Object]

2. instanceof

原理:判断对象的原型链中是不是能找到类型的 prototype。

使用方法:object为实例对象,constructor为构造函数。

object instanceof constructor

构造函数通过new可以实例对象,instanceof能判断这个对象是否是之前那个构造函数生成的对象。

示例:

// 定义构建函数
let Car = function() {}
let benz = new Car()
benz instanceof Car // true
let car = new String('xxx')
car instanceof String // true
let str = 'xxx'
str instanceof String // false

缺点:只能准确地判断复杂引用数据类型,但是不能正确判断基础数据类型。

3. Array.isArray()

功能:用于确定传递的值是否是一个数组。

console.log(Array.isArray([1, 3, 5]));
// Expected output: true

console.log(Array.isArray('[]'));
// Expected output: false

console.log(Array.isArray(new Array(5)));
// Expected output: true

4. 区别

  • 当检测 Array 实例时,Array.isArray 优于 instanceof,因为 Array.isArray 能跨领域工作。
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const xArray = window.frames[window.frames.length - 1].Array;
const arr = new xArray(1, 2, 3); // [1, 2, 3]

// 正确检查 Array
Array.isArray(arr); // true
// arr 的原型是 xArray.prototype,它是一个不同于 Array.prototype 的对象
arr instanceof Array; // false

  • Array.isArray()是ES5新增的方法,当不存在 Array.isArray() ,可以用
    Object.prototype.toString.call() 实现。
if (!Array.isArray) {
  Array.isArray = function(e) {
    return Object.prototype.toString.call(e) === '[object Array]';
  };
}
  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值