ES6之Arrayfrom方法

9次阅读

共计 1117 个字符,预计需要花费 3 分钟才能阅读完成。

ES6 之 Array.from() 方法

Array.from() 方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组。

== 只要是部署了 Iterator 接口 == 的数据结构,Array.from 都能将其转为数组。

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

1)arrayLike:想要转换成数组的伪数组对象或可迭代对象;

2)mapFn:如果指定了该参数,新数组中的每个元素会执行该回调函数;

3)thisArg:可选参数,执行回调函数 mapFn 时 this 对象。

⚠️该方法的返回值是一个新的数组实例(真正的数组)。

使用:

  1. 将类数组对象转换为真正数组:
let a= {
  0: "tom",
  1: "65",
  2: "男",
  3: ["a", "b", "c"],
  length: 4
};

console.log(Array.from(a))
//["tom", "65", "男", Array(3)]

类数组要求:

(1)该类数组对象必须具有 length 属性,用于指定数组的长度。如果没有 length 属性,那么转换后的数组是一个空数组。

(2)该类数组对象的属性名必须为数值型或字符串型的数字

2. 将 Set 解构的数据转换为数组

let arr = [1,2,3,4,5,6,7,8,9]
let set = new Set(arr)
console.log(Array.from(set))  // [1,2,3,4,5,6,7,8,9]

3. 将字符串转换为数组

let  str = 'hello world!';
console.log(Array.from(str)) // ["h", "e", "l", "l", "o", "","w","o","r","l","d","!"]

相当于 str.split(”)

4. 复制数组

let arr = [1,2,3,4,5];
let arr2 = Array.from(arr);
// 相当于 let arr2 = [...arr]
console.log(arr)        // [1,2,3,4,5]
console.log(arr2)        // [1,2,3,4,5]

5. 类似于数组的 map 方法

用来对每个元素进行处理,将处理后的值放入返回的数组。如下:

let arr = [1,2,3,4,5]
let set = new Set(arr)
console.log(Array.from(set, item => item + 1)) // [2,3,4,5,6]

6. 返回数组的真正长度

function countSymbols(string) {return Array.from(string).length;
}

7. 控制函数执行的次数

Array.from({length: 2}, () => 'jack')
// ['jack', 'jack']

正文完
 0