JS中伪数组转为数组

1. 伪数组定义

伪数组即为arrayLike,是一种按照索引来存储数据,且具有length属性的对象。

常见的伪数组有我们平时用的多的arguments

还有通过docuemnt.querySelector等获取的元素节点数组

const fun = function(){
    console.log(arguments)
}
fun(1,2) // {0: 1, 1: 2, length: 2}

2. 创建一个伪数组

  1. 具有length属性
  2. 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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值