一、伪数组(类数组)特点
1、具有length属性;
2、可以使用下标访问数据;
3、不具有数组的方法, 比如push()、pop()等。
二、常见伪数组
1、字符串:
let str = 'hello';
console.log(str.length) // 5
console.log(str[1]) // e
2、function的arguments对象:
let fun = function() {
console.log(arguments.length); // 3
console.log(arguments[1]); // 2
}
fun(1, 2, "abc");
3、含有length属性的对象:
let obj = {
length : 2
};
console.log(obj.length); // 2
console.log(obj[1]); // undefined
obj[1] = 'hello';
console.log(obj); // {1: 'hello', length: 2}
三、伪数组转为数组的方法
1、使用Array.prototype.slice.call()或者Array.prototype.slice.apply();
2、使用[].slice.call()或者[].slice.apply();这种方法和上面的方法是一样的,但是上面的方式效率相对较高;
3、使用Array.from();
4、使用Array.of();
5、使用new Array();
let str = 'hello';
console.log(str.length) // 5
console.log(str[1]) // e
console.log(Array.prototype.slice.call(str)) // ['h', 'e', 'l', 'l', 'o']
console.log(Array.prototype.slice.apply(str)) // ['h', 'e', 'l', 'l', 'o']
console.log(Array.from(str)); // ['h', 'e', 'l', 'l', 'o']
console.log(Array.of(...str)); // ['h', 'e', 'l', 'l', 'o']
console.log(new Array(...str)); // ['h', 'e', 'l', 'l', 'o']
let fun = function() {
console.log(arguments.length); // 3
console.log(arguments[1]); // 2
console.log([].slice.call(arguments)); // [1, 2, 'abc']
console.log([].slice.apply(arguments)); // [1, 2, 'abc']
console.log(Array.from(arguments)); // [1, 2, 'abc']
console.log(Array.of(...arguments)); // [1, 2, 'abc']
console.log(new Array(...arguments)); // [1, 2, 'abc']
}
fun(1, 2, "abc");
let obj = {
length : 2
};
console.log(obj.length); // 2
console.log(obj[1]); // undefined
obj[1] = 'hello';
console.log(obj); // {1: 'hello', length: 2}
console.log(Array.prototype.slice.call(obj)); // [empty, 'hello']
console.log([].slice.call(obj)); // [empty, 'hello']
console.log(Array.from(obj)); //[undefined, 'hello']
// console.log(Array.of(...obj)); // TypeError: Found non-callable @@iterator
// console.log(new Array(...obj)); // TypeError: Found non-callable @@iterator
参考文章: