1. 伪数组定义
伪数组即为arrayLike,是一种按照索引来存储数据,且具有length属性的对象。
常见的伪数组有我们平时用的多的arguments
还有通过docuemnt.querySelector等获取的元素节点数组
const fun = function(){
console.log(arguments)
}
fun(1,2) // {0: 1, 1: 2, length: 2}
2. 创建一个伪数组
- 具有length属性
- length的值需要大于最大索引值
const arrlike = {
0: 'apple',
3: 'orange',
length: 4
};
// apple 0
// orange 3
[].forEach.call(arrlike, (item,index)=>console.log(item,index))
// 如果将length改为2
const arrlike2 = {
0: 'apple',
3: 'orange',
length: 2
}
// apple 0 只能打印一个
[].forEach.call(arrlike, (item,index)=>console.log(item,index))
3. 伪数组转为数组
Array.from()
const fun = function(){
const args = Array.from(arguments)
console.log(args)
}
fun(1,2,3) // [1,2,3]
es6的三点符 ...(arguments)
const fun = function(){
const args = [...arguments]
console.log(args)
}
fun(1,2,3) // [1,2,3]
[].slice.call(arguments)
const fun = function(){
const args = [].slice.call(arguments)
console.log(args)
}
fun(1,2,3) // [1,2,3]
[].splice.call(arguments)
const fun = function(){
const args = [].splice.call(arguments, 0)
console.log(args)
}
fun(1,2,3) // [1,2,3]
[].forEach.call(arguments, (item)=>{})
const fun = function(){
[].forEach.call(arguments, (item,index)=>{
console.log(item, index)
})
}
// apple 0
// orange 1
fun('apple', 'orange')
[].concat.apply([],arguments)
const fun = function(){
const args = [].concat.apply([],arguments)
console.log(args)
}
fun(1,2,3) // [1,2,3]
网友评论