JavaScript中Array.from()方法的用法

1. 介绍

作用:将一个伪数组对象或者可迭代的任意对象转换为一个真正的数组

语法: Array.from(arrayLike [, mapFunction [, thisArg]])

  • arrayLike:必传参数,指定需要转换为数组的伪数组对象或任意可迭代的对象
  • mapFunction:可选参数,mapFunction( item, index ){} 是在集合中的每个项目上调用的方法,返回的值插入到新集合中
  • thisArg: 可选参数,执行回调函数 mapFunction 时的 this 对象,很少用

2. 将伪数组转换为真正的数组

2.1 DOM 集合

// 最常见的伪数组就是 DOM 集合
let lis = document.querySelectorAll('ul > li')
let newLis = Array.from(lis)
console.log(newLis);

2.2 函数中的 arguments 关键字

function sum() {
    // reduce() 方法接收的两个参数分别代表的是上一次返回的值,和这一次遍历的值
    let arr = Array.from(arguments).reduce((x, y) => x + y)
    console.log(arr)
    // 6
}
sum(1, 2, 3)

2.3. 将字符串转换为数组

let str = 'JavaScript'
let arr = Array.from(str)
console.log(arr)
// ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']

2.4 带有 length 的对象

let obj = {
    0: '张三',
    1: 59,
    2: '男',
    length: 3,
}

console.log(obj)
// { '0': '张三', '1': 59, '2': '男', length: 3 }

let arr = Array.from(obj)
console.log(arr)
// [ '张三', 59, '男' ]

/***  如果将上面代码中的 length 去掉,返回的就是一个长度为 0 的空数组  ***/

将上面的代码再次进行改进:将对象中的 key 修改为 字符串类型

let obj = {
    '0': '张三',
    'age': 59,
    'sex': '男',
    length: 3,
}

console.log(obj)
// { '0': '张三', age: 59, sex: '男', length: 3 }

let arr = Array.from(obj)
console.log(arr)
// [ '张三', undefined, undefined ]

虽然可以返回数组,但是除了字符串类型的数值,其他的字符串均被识别为了 undefined

由此可见,要将一个伪数组转换为一个真正的数组,需要满足以下两个条件:

  1. 伪数组必须携带 length 属性,用于指定数组的长度。如果没有,转换出来的就是一个空数组
  2. 伪数组对象的属性值必须是数值型或者字符串类型的数值

3. 数组去重

// 原理:利用 set 集合会去除重复项的能力
let arr = [1, 2, 3, 1]
let set = new Set(arr)
console.log(set)
// Set(3) { 1, 2, 3 }

let newArr = Array.from(set)
console.log(newArr)
// [ 1, 2, 3 ]

// 打包成函数
function unique(arr) {
    return Array.from(new Set(arr))
}
console.log(unique([1, 1, 2, 3, 3]))
// [ 1, 2, 3 ]

4. Array.from() 方法的第二项参数

第二项参数为一个函数,会在每个元素上进行调用,返回的值插入到新集合中。

let arr = [10, 22, 30]
let newArr = Array.from(arr, (item) => item * 2)
console.log(newArr)
// [ 20, 44, 60 ]

// 类似于 map() 方法
let newArr2 = arr.map((item) => item * 2)
console.log(newArr2);
// [ 20, 44, 60 ]
posted @ 2022-11-01 01:41  如是。  阅读(481)  评论(0编辑  收藏  举报