ES6的Array.from()和Array.fill()方法

今天处理数据时用到了Array.from()和Array.fill()方法,平时用的不多,这里记一下。

 

我的需求是要把字符串'abc',处理为[{exaple: 'abc_001.bcd'}, {exaple: 'abc_002.bcd'}, {exaple: 'abc_003.bcd'}]

处理方法如下:

// 创建数组['abc', 'abc', 'abc']
let arr = new Array(3).fill('abc');

arr = Array.from(covers, (item, index) => { return { example: `${item}_00${index + 1}.bcd` } });

 

  

一、Array.fill()

Array.fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。

例子:

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

二、Array.from()

Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。

例子:

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

  参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from

 

END--------------------------

你藏在我衣服的針線裡面,我藏在你口袋裡面。

 

posted @ 2020-03-28 00:00  麦豇豆  阅读(1011)  评论(0编辑  收藏  举报