DIV CSS 佈局教程網

ES6 陣列擴充方法整理:from、of、copyWithin
編輯:關於JavaScript     

Array.from:把類陣列變成真陣列

操作 DOM 是日常。假設要抓出頁面上所有 input,挑出 type 為 button 的,再掛上點擊事件,直覺寫法大概像這樣:

var inputObjs = document.getElementsByTagName('input');
for (var i = 0; i < inputObjs.length; i++) {
    if (inputObjs[i].type === 'button') {
        inputObjs[i].onclick = function () {
            return;
        }
    }
}

能跑,沒問題。但我們都知道陣列方法比 for 迴圈好用得多,比如 ES5 的 forEach。可以直接用在這裡嗎?不行:

var inputObjs = document.getElementsByTagName('input');
inputObjs.forEach();
// Uncaught TypeError: inputObjs.forEach is not a function

因為 DOM 集合根本不是真正的 Array,它是類陣列物件。舊做法是借 call 來「冒充」:

var inputObjs = document.getElementsByTagName('input');
console.info(inputObjs);              // HTMLCollection
console.info([].slice.call(inputObjs)); // Array

可行,但語意繞、可讀性也差。ES6 提供了更直接的 Array.from:

var inputObjs = document.getElementsByTagName('input');
console.info(Array.from(inputObjs)); // Array

更妙的是,from 不只吃類陣列,幾乎任何型別都能丟進去,只是結果各異:

let str = 'google';
console.log(Array.from(str)); // ["g", "o", "o", "g", "l", "e"]

let num = 234;
console.log(Array.from(num)); // []

let bol = false;
console.log(Array.from(bol)); // []

let obj = { foo: 'foo', bar: 'bar' };
console.log(Array.from(obj)); // []

let superObj = { 0: 'foo', 1: 'bar', length: 2 };
console.log(Array.from(superObj)); // ["foo", "bar"]

規律其實很清楚:凡是能用 for 迴圈逐項取出內容的,轉出來就不是空陣列。字串可以,具備數字鍵值對且有 length 的物件也可以。

順帶一提,用 jQuery 選擇器拿到的那個物件,結構就跟最後這個 superObj 一模一樣——這也是為什麼 jQuery 集合能用索引取值、有 length 屬性。

Array.of:把值變成陣列

建立陣列有兩條路,構造函數式與字面量:

let arr = Array(1, 2, 3);
let arr2 = [1, 2, 3];

Array.of 是對構造函數式的補救方案:

console.log(Array.of(1, 2, 3)); // [1, 2, 3]

看起來跟 Array() 差不多,為何還需要它?問題出在參數只有一個的時候:

console.log(Array());    // []
console.log(Array(1));   // [empty × 1],長度為 1 的陣列
console.log(Array(1, 2)); // [1, 2]

單一參數被解釋成「長度」,多參數才當成元素,很容易誤用。而 Array.of 的參數永遠代表元素本身:

console.log(Array.of());   // []
console.log(Array.of(1));  // [1]
console.log(Array.of(1, 2)); // [1, 2]

copyWithin:陣列內部的自我複製

copyWithin 用來在陣列內部搬移並覆寫內容,接受三個參數:目標起始位置、來源起始位置、來源結束位置。

[1, 2, 3, 4, 5].copyWithin(0, 3)        // [4, 5, 3, 4, 5]
[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}

var i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, 5]

負數索引從尾端起算,這點跟 slice、splice 的慣例一致。若平台上 TypedArray 尚未支援這個方法,可以借用通用寫法:

[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

以上三個方法,幾乎涵蓋了日常處理陣列最常遇到的痛點:型別轉換、安全建構、原位搬移。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved