js将伪数组转换为数组

常见的伪数组有

  • 由DOM元素组成的一组集合
  • DOM元素的children属性
  • 函数内置对象arguments
  • Set数据结构

伪数组 ----> 数组 的方法

  • Array.from()
  • …扩展运算符

看如下代码

function fun() {
  console.log(arguments)
  console.log('[...arguments]', [...arguments])
  console.log('Array.from(arguments)', Array.from(arguments))
}
fun(1, 2, 3, 4)
const s = new Set([5, 6, 7, 8, 9])
console.log(s)
console.log('[...s]', [...s])
console.log('Array.from(s)', Array.from(s))

代码结果

[Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 }
[...arguments] [ 1, 2, 3, 4 ]
Array.from(arguments) [ 1, 2, 3, 4 ]
Set { 5, 6, 7, 8, 9 }
[...s] [ 5, 6, 7, 8, 9 ]
Array.from(s) [ 5, 6, 7, 8, 9 ]

扩展运算符更多应用场景

  • 合并数组,对象
console.log([...[1, 2, 3, 4], ...[10, 20, 30, 40]])
console.log({
  ...{ uname: 'dj' },
  ...{
    age: 100,
    say() {
      console.log('say function')
    }
  }
})
代码结果
[
   1,  2,  3,  4,
  10, 20, 30, 40
]
{ uname: 'dj', age: 100, say: [Function: say] }
  • 伪数组 ----> 数组 看最上面的代码
  • 向数组添加多个元素
let arr = [1, 2, 3, 4]
arr.push(...[5, 6, 7])
console.log(arr)
代码结果
[
  1, 2, 3, 4,
  5, 6, 7
]
  • 使用Math对象求数组的最大最小值
let arr = [1, 2, 3, 4]
console.log(Math.max(...arr)) // 4
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值