何为伪数组
伪数组有两个特点:
- 具有length属性,其他属性(索引)为非负整数
- 但是却不具备数组的方法
也就是看起来像是数组,然而并不是…
举个例子看看
- 函数内部的arguments
function testArguments(a, b, c) {
console.log(`arguments is array: ${Array.isArray(arguments)}`);
console.log(arguments[0]);
console.log(arguments[1]);
console.log(arguments[2]);
}
testArguments(1,2,3);
image.png
如何判断真伪数组
使用instanceof 方法
使用Array.isArray()方法: 未必准确,见下文, 使用伪数组.proto = Array.prototype;转换后不可用。
伪数组.constructor === Array; 适用于带constructor的场景
Object.prototype.toString.call(arr) === ‘[object Array]’
尝试一下:
function testArguments(a, b, c) {
console.log(`arguments is array: ${Array.isArray(arguments)}`);
console.log(`arguments is array: ${arguments instanceof Array}`);
console.log(`arguments is object: ${arguments instanceof Object}`);
const newArguments = Array.prototype.slice.call(arguments);
console.log(`newArguments is array: ${Array.isArray(newArguments)}`);
console.log(`newArguments is array: ${newArguments instanceof Array}`);
console.log(`newArguments is object: ${newArguments instanceof Object}`);
}
testArguments(1,2,3);
image.png
[图片上传中...(image.png-58e6ee-1637663233310-0)]
如何把伪数组转换成数组
Array.prototype.slice.call(); / Array.prototype.slice.apply();
原型继承: 伪数组.proto = Array.prototype;arguments 无影响正常使用
ES6中数组的新方法 from()
方法一: Array.prototype.slice.call(); / Array.prototype.slice.apply();
function testArguments(a, b, c) {
console.log(`arguments is array: ${Array.isArray(arguments)}`);
console.log(`arguments is array: ${arguments instanceof Array}`);
const newArguments = Array.from(arguments);
console.log(`newArguments is array: ${Array.isArray(newArguments)}`);
console.log(`newArguments is array: ${newArguments instanceof Array}`);
}
testArguments(1,2,3);
image.png
网友评论