ES6(ECMAScript 2015)為 JavaScript 帶來了全面升級,數組作為最常用的數據結構自然也收穫不少新特性。下面按「靜態方法、操作方法、遍歷方法」三類,把這些新增能力梳理一遍。
主要用途是把兩類對象轉成真數組:類數組對象(array-like object)和可遍歷對象(iterable)。
ES5 時代常見的轉換寫法是借 call 挪用 slice:
function cast() {
return Array.prototype.slice.call(arguments);
}
cast('a', 'b', 'c', 'd'); // ["a", "b", "c", "d"]
// 也可以簡寫
function cast() {
return [].slice.call(arguments);
}
ES6 中直接用 Array.from 表達意圖更清晰。所謂類數組對象,本質特徵只有一條——必須有 length 屬性:
let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 };
console.log(Array.from(arrayLike)); // ["a", "b", "c"]
擴展運算符 ... 也能把某些數據結構轉為數組,但它依賴遍歷器接口 Symbol.iterator:
function cast() { return [...arguments]; }
cast('a', 'b', 'c'); // ["a", "b", "c"]
如果對象沒有部署 iterator 接口,擴展運算符就無能為力,這正是 Array.from 更通用的地方。
Array.from 接受三個參數,只有第一個必填:
· input:要轉換的類數組對象或可遍歷對象
· map:類似數組的 map,便於在轉換同時加工元素
· context:綁定 map 回調中的 this
// 字符串與 Set 都部署了 iterator,可以直接轉
let arr = Array.from('w3cplus.com');
// ["w","3","c","p","l","u","s",".","c","o","m"]
let namesSet = new Set(['a', 'b']);
let arr2 = Array.from(namesSet); // ["a","b"]
// 傳入真正的數組,返回一份內容相同的新數組
Array.from([1, 2, 3]); // [1, 2, 3]
// 第二個參數等於 map,可順帶做運算
Array.from(arrayLike, x => x * x);
Array.from([1, 2, 3], (x) => x * x); // [1, 4, 9]
// 借助 length 控制生成次數,用法非常靈活
Array.from({ length: 2 }, () => 'jack'); // ['jack', 'jack']
還有一個實用場景是統計字符串長度。由於 Array.from 能正確處理 Unicode 碼點,可以避免 JavaScript 把大於 的字符算作兩個的歷史 bug:
function countSymbols(string) {
return Array.from(string).length;
}
// 配合 map 還能返回各元素的類型
function typesOf() {
return Array.from(arguments, value => typeof value);
}
typesOf(null, [], NaN); // ['object', 'object', 'number']
它的作用是彌補 Array 構造函數的重載歧義。因為參數個數不同,new Array() 的行為差別很大:
new Array(); // [] new Array(undefined); // [undefined] new Array(1); // [undefined x 1] —— 被當作長度 new Array(3); // [undefined x 3] new Array(1, 2); // [1, 2] new Array(-1); // RangeError: Invalid array length
Array.of 的行為則完全統一,一個參數就是一個元素:
Array.of(); // [] Array.of(undefined); // [undefined] Array.of(1); // [1] Array.of(3); // [3] Array.of(1, 2); // [1, 2] Array.of(-1); // [-1]
它的實現非常樸素,本質就是 slice 借用:
Array.of = function of() {
return Array.prototype.slice.call(arguments);
};
在數組內部把指定位置的項複製到其他位置(會覆蓋原有內容),並返回當前數組,屬於修改原數組的操作。
Array.prototype.copyWithin(target, start = 0, end = this.length)
· target(必填):從該位置開始替換
· start(可選):從該位置開始讀取,默認 0,負值表示從右向左數
· end(可選):讀取到該位置結束,默認為 length,負值同樣從右數
var items = [1, 2, 3, , , , , , , ,];
items.copyWithin(6, 1, 3);
// [1, 2, 3, undefined × 3, 2, 3, undefined × 2]
[1, 2, 3, 4, 5].copyWithin(0, 3, 4); // [4, 2, 3, 4, 5]
[1, 2, 3, 4, 5].copyWithin(0, -2, -1); // [4, 2, 3, 4, 5]
// 也可作用於類數組對象
[].copyWithin.call({ length: 5, 3: 1 }, 0, 3); // {0: 1, 3: 1, length: 5}
// 支持 TypedArray
var i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, 5]
用指定值填充數組,非常適合初始化:
['a', 'b', 'c'].fill(0); // [0, 0, 0] new Array(3).fill(0); // [0, 0, 0]
第二、三個參數分別指定起始與結束位置:
['a', 'b', 'c', , ,].fill(0, 2); // ['a', 'b', 0, 0, 0] new Array(5).fill(0, 0, 3); // [0, 0, 0, undefined x 2]
填充值可以是任意類型,包括對象與函數:
new Array(3).fill({}); // [{}, {}, {}]
new Array(3).fill(function foo() {}); // [foo, foo, foo]
要注意 fill 不接受映射函數,三個元素拿到的是同一個引用,若填的是對象,改動其中一個會影響全部。
找出第一個符合條件的數組成員。參數是回調函數,依次執行直到某項返回 true,然後返回該項;都沒有命中則返回 undefined。
[1, 2, 3, 4, 5].find(item => item > 2); // 3
[1, 2, 3, 4, 5].find((item, i) => i === 3); // 4
[1, 2, 3, 4, 5].find(item => item === Infinity); // undefined
// 回調依次接收:值、下標、原數組
[1, 5, 10, 15].find(function (value, index, arr) {
return value > 9;
}); // 10
與 find 幾乎一致,只是返回下標而非元素;未命中返回 -1。
[1, 2, 3, 4, 5].findIndex(item => item > 2); // 2 [1, 2, 3, 4, 5].findIndex((item, i) => i === 3); // 3 [1, 2, 3, 4, 5].findIndex(item => item === Infinity); // -1
這兩個方法還有一個重要價值:能正確找到 NaN,彌補了 indexOf 的短板。
[NaN].indexOf(NaN); // -1,找不到 [NaN].findIndex(y => Object.is(NaN, y)); // 0,找到了
ES6 新增 entries()、keys()、values(),都返回一個遍歷器對象,可用 for...of 消費。區別在於:keys 遍歷鍵名,values 遍歷鍵值,entries 遍歷鍵值對。
for (let index of ['a', 'b'].keys()) {
console.log(index); // 0 / 1
}
for (let elem of ['a', 'b'].values()) {
console.log(elem); // 'a' / 'b'
}
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem); // 0 "a" / 1 "b"
}
不用 for...of 也可以手動調用 next():
let letter = ['a', 'b', 'c']; let entries = letter.entries(); console.log(entries.next().value); // [0, 'a'] console.log(entries.next().value); // [1, 'b'] console.log(entries.next().value); // [2, 'c']
初次接觸 ES6 時,這些方法容易看著有點暈,但只要抓住幾條主線就清楚了:要轉換用 Array.from,要批量生成用 Array.of 或 fill,要查找用 find/findIndex,要遍歷鍵值用 entries。另外牢記 copyWithin 與 fill 都會修改原數組,而 slice、concat 則返回新數組,這個區別在寫純函數式代碼時尤為關鍵。