美文网首页
JS中伪数组转数组

JS中伪数组转数组

作者: 子皙丶 | 来源:发表于2024-06-04 16:08 被阅读0次

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]

相关文章

  • js中伪数组转真数组

    一、什么是真数组(数组) 所谓真数组,其实可以直接称为:数组。当一个对象具有以下特点时,可以称为数组: 可以按照索...

  • call,apply,bind的实际应用

    call,apply,bind详解传送门 求数组中的最大和最小值 将伪数组转化为数组 js中的伪数组(例如通过do...

  • JS 将伪数组转换成数组 🎄

    本文简介 点赞 + 关注 + 收藏 = 学会了 在 JS 中,伪数组 是非常常见的,它也叫 类数组。伪数组可能会给...

  • JS 将伪数组转换成数组

    本文简介 点赞 + 关注 + 收藏 = 学会了 在 JS 中,伪数组 是非常常见的,它也叫 类数组。伪数组可能会给...

  • 2019前端经典面试题

    1.简述对标签语义化的理解。 2. css实现垂直水平居中 3. js中哪些是伪数组?如何将伪数组转化为标准数组?...

  • 伪数组

    1、伪数组特点 2、常见伪数组 3、伪数组与数组的区别 4、伪数组转成真数组

  • js中的数组和伪数组

  • 在javascript中什么是伪数组?如何将伪数组转换为标准数组

    伪数组?一听到这个词懵了,知道js中有数组,竟然还有伪数组?在面试过程中,面试官问的有些东西我们不是不会,而是被专...

  • js伪数组

    伪数组是一个含有length属性的json对象,它是按照索引的方式存储数据,它并不具有数组的一些方法. 1. 将伪...

  • 关于javascript中的伪数组

    1、什么是js伪数组? 请看下面一段代码: 控制台输出: 上图就是一个伪数组,长相很像数组,但是将他的原型 _pr...

网友评论

      本文标题:JS中伪数组转数组

      本文链接:https://www.haomeiwen.com/subject/dypyqjtx.html