1.什么是伪数组?
我的理解是看上去像数组,其实他真正的数据类型是obj;
arguments还是一组实参的集合,当调用函数,不确定要放多少实参时,我们就可以用到。如下代码,我们可以放任意多的形参
<script>
function aa(){
console.log(arguments);
}
aa(1,2,"8","ni")
</script>
输出结果如下图,看上去是数组,其实是个对象,这就是伪数组
2. 如何将伪数组转真数组?
下面有三种常用方式
1)[ ].slice.call(arguments)
<script>
function aa(){
console.log(arguments);
let a=[].slice.call(arguments)
console.log(a);
}
aa(1,2,"8","ni")
</script>
2) array.from(arguments)
<script>
function aa(){
console.log(arguments);
let b=Array.from(arguments)
console.log(b);
}
aa(1,2,"8","ni")
</script>
3) [...arguments]
<script>
function aa(){
console.log(arguments);
let c=[...arguments]
console.log(c);
}
aa(1,2,"8","ni")
</script>
三种方式都能得到以下结果