Array.from()的6种常见用法

Array.from()是一个用于从类数组对象可迭代对象创建新数组的静态方法。
基本语法:

Array.from(arrayLike[, mapFunction[, thisArg]])

arrayLike: 类数组对象或可迭代对象,用于创建新数组
mapFunction (可选): 对数组中的每个元素进行映射的函数
thisArg (可选): 执行 mapFunction 时,用作 this 的值。

1. 字符串转数组

const str = 'hello';
const newArray = Array.from(str);
console.log(newArray); // ['h', 'e', 'l', 'l', 'o']
// 相当于 str.split('')

2. 用Set 或 Map创建数组

const set = new Set([1, 2, 3]);
const newArray = Array.from(set);
console.log(newArray); // [1, 2, 3]

3. 对元素进行迭代处理

const numbers = [1, 2, 3];
const squaredNumbers = Array.from(numbers, x => x * x);
console.log(squaredNumbers); // [1, 4, 9]
const str = 'hello'

const strArr = Array.from(str,(s) =>s+'_')
console.log(strArr);//["h_", "e_", "l_", "l_", "o_"]
console.log(strArr.join(''));// "h_e_l_l_o_"

4. 类数组对象转成真正的数组

什么是类数组对象?

const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
const newArray = Array.from(arrayLike);
console.log(newArray); // ['a', 'b', 'c']
    function exampleFn() {
      console.log(arguments); // { 0: 1, 1: 2, 2: "a" ,length:3,...} 类数组对象
      console.log(Array.from(arguments))//[1, 2, "a"] 真正的数组
      console.log([...arguments])//[1, 2, "a"]
    }
    exampleFn(1, 2, 'a')

5. 数组、字符串的去重

    const arr = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArray = Array.from(new Set(arr));
    const uniqueArray2 =[...new Set(arr)]
    const uniqueArray3 = _.uniq(arr)// 使用lodash中的方法
    
    console.log(uniqueArray); // [1, 2, 3, 4, 5]
    console.log(uniqueArray2); // [1, 2, 3, 4, 5]
    console.log(uniqueArray3); // [1, 2, 3, 4, 5]

6. 创建指定长度的数组

	// 数组里创建3个空数组
    const newArr = Array.from({length:3},() =>[])
    console.log(newArr)//[[],[],[]]
     const newArr2 = Array.from({ length:5}, (_, index) => index + 1);
    console.log(newArr2); // [1, 2, 3, 4, 5]
    // 数组里创建3个空对象
    const newArr = Array.from({length:3},() =>({})
    console.log(newArr)//[{},{},{}]

注意

const arr = Array.from({length: 5}, () => {})
console.log(arr);//[undefined, undefined, undefined, undefined, undefined]

映射函数 () => {} 不会改变数组的元素的实际值,因为它返回的是一个空函数。因此,使用 Array.from 时,每个元素都会被映射为 undefined。
而映射函数 () => ({}) 返回一个新的空对象。每次映射函数调用时,都会返回一个新的对象,因此每个数组元素都将包含一个新的空对象。

  • 14
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值