ES6 學習筆記之數組的拓展
- 2020 年 1 月 5 日
- 筆記
ES6 在數組上改變還是比較多的,主要是為了彌補 ES5 一些方法的不足或新增一些方法,但大體這些方法在其他語言中也都見過,所以操作和使用起來不難,可能名字不一樣,但看一看就知道如何使用了。
Array.from() 方法
const arrayLike = { '0': 'a', '1': 'b', '2': 'c', 'length': 3 }; // ES6 寫法 let arr1 = Array.from(arrayLike); arr1.forEach((arr) => { console.log(arr); })
從字元串中初始化一個數組
let arr2 = Array.from('Hello'); console.log(arr2); // [ 'H' 'e' 'l' 'l' 'o' ]
從 Set 結構中初始化一個數組
let arr3 = Array.from(new Set(['a', 'b', 'c', 'd'])); console.log(arr3); // [ 'a' 'b' 'c' 'd' ]
轉換一個表明了有 length 屬性的對象,由於僅指定了長度為 3,而 3 個元素均沒有表明,所以都是 undefined。
let arr4 = Array.from({length: 3}); console.log(arr4); // [ undefined, undefined, undefined ]
Array.of() 方法
let arr5 = Array.of(1, 2, 3, 4, 5); console.log(arr5);
copyWithin() 方法
將指定位置的元素複製到當前數組的指定位置,就是會改變原數組的內容
- target(必需):從該位置開始替換數據。
- start(可選):從該位置開始讀取數據,默認為0。如果為負值,表示倒數。
- end(可選):到該位置前停止讀取數據,默認等於數組長度。如果為負值,表示倒數。
[1, 2, 3, 4, 5].copyWithin(0, 3); console.log(arr5); // [ 4, 5, 3, 4, 5 ]
find() 方法
const testArr = [1, 3, -5, 10]; // 找小於 0 的元素 console.log(testArr.find((n) => n < 0)); // 找大於 9 的元素 console.log(testArr.find((value, index, arr) => { return value > 9; }));
keys() values() entries()
for (let index of ['a', 'b', 'c'].keys()) { console.log(index); } for (let elem of ['a', 'b', 'c'].values()) { console.log(elem); } for (let [index, elem] of ['a', 'b', 'c'].entries()) { console.log(`${index}: ${elem}`); }