javascript 类(伪)数组和数组的区别
1:类(伪)数组和数组的区别
相同点:都具有length属性和索引元素
不同点:类数组没有任何Array属性和Array方法(比如push)
2:原因
最常用的类数组是 arguments
:
function test(){
console.log(typeof arguments)
}
test();
可以发现输出的类型是 object
说明它有数组的一些特性,而不是数组的类型。
图片中的对象方法
为非静态方法,像 assign(),create() 这种对象静态方法是不能被继承的。
Array 继承于 Object:
Array 是 儿子
;
Object 是 父亲
;
可想而知,这些技能是父辈所没有的,但是孩子们已经学会了这些技能,而且类数组
在父辈那一代,所以他们不具备孩子们的技能。
3:将类(伪)数组转成数组
方法一:Array.from
const args = Array.from(arguments);
方法二:拓展运算符
const args = [...arguments];
方法三:[].slice.call
const args = [].slice.call(arguments);;
稍微记住几个就行。
方法四:Array.prototype.slice.call
const args = Array.prototype.slice.call(arguments);;
方法五:Array.prototype.splice.call
const args = Array.prototype.splice.call(arguments, 0);
方法六:Array.prototype.concat.apply
const args = Array.prototype.concat.apply([], arguments);