javascript 有哪些是伪数组(类数组)

2025-10-22 13:44:02

伪数组定义

拥有length属性,其它属性(索引)为非负整数(对象中的索引会被当做字符串来处理,这里你可以当做是个非负整数串来理解)

不具有数组所具有的方法

伪数组是一个 Object, 而真实的数组是一个 Array

伪数组存在的意义

可以让普通的对象也能正常使用数组的很多算法

常见的伪数组

function 参数 arguments

DOM 对象列表,比如通过 document.getElementsByTags 得到的列表

jQuery 对象,比如 $("div")

如何判断真数组、伪数组?

以下是判断真数组的方法:

const a = [];

const b = {};

console.log(a instanceof Array);//true

console.log(a instanceof Object);//true

console.log(b instanceof Array);//false

const a = ['Hello','world'];

const b = {0:'Hello',1:'world'};

const c = 'Hello world';

Object.prototype.toString.call(a);//"[object Array]"

Object.prototype.toString.call(b);//"[object Object]"

Object.prototype.toString.call(c);//"[object String]"

伪数组如何转换成真数组?

Array.prototype.slice.call(arguments)

// 或

[].slice.call(arguments)