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

今天處理數據時用到了Array.from()和Array.fill()方法,平時用的很少,這裏記一下。數組

 

個人需求是要把字符串'abc',處理爲[{exaple: 'abc_001.bcd'}, {exaple: 'abc_002.bcd'}, {exaple: 'abc_003.bcd'}]spa

處理方法以下:code

// 建立數組['abc', 'abc', 'abc']
let arr = new Array(3).fill('abc');

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

 

  

1、Array.fill()

Array.fill() 方法用一個固定值填充一個數組中從起始索引到終止索引內的所有元素。不包括終止索引。對象

例子:blog

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索引

2、Array.from()

Array.from() 方法從一個相似數組或可迭代對象建立一個新的,淺拷貝的數組實例。ip

例子:字符串

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/fromget

 

END--------------------------it

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

相關文章
相關標籤/搜索