ES6數組對象新增方法

1. Array.from()

Array.from方法用於將兩類對象轉爲真正的數組:類數組的對象( array-like object )和可遍歷( iterable )的對象(包括 ES6 新增的數據結構 Set 和Map )。html

let arrayLike = {  
  '0': 'a',  
  '1': 'b',  
  '2': 'c',  
  length: 3  
};  
// ES5 的寫法  
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']  
// ES6 的寫法  
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']  
  
// NodeList 對象  
let ps = document.querySelectorAll('p');  
Array.from(ps).forEach(function (p) {  
  console.log(p);  
});  
// arguments 對象  
function foo() {  
var args = Array.from(arguments);  
// ...  
}  

//字符串轉換爲字符數組str.split('') Array.from(
'hello') // ['h', 'e', 'l', 'l', 'o'] let namesSet = new Set(['a', 'b']) Array.from(namesSet) // ['a', 'b'] Array.from({ length: 3 }); // [ undefined, undefined, undefined ]

對於尚未部署該方法的瀏覽器,能夠用Array.prototype.slice方法替代:算法

const toArray = (() =>
  Array.from ? Array.from : obj => [].slice.call(obj)
)();

Array.from還能夠接受第二個參數,做用相似於數組的map方法,用來對每一個元素進行處理,將處理後的值放入返回的數組。數組

Array.from(arrayLike, x => x * x);  
//  等同於  
Array.from(arrayLike).map(x => x * x);  
Array.from([1, 2, 3], (x) => x * x)  
// [1, 4, 9]  
//Array.from回調函數
var arr1 = Array.from([1,2,3], function(item){
    return item*item;
});
var arr2 = Array.from([1,2,3]).map(function(item){
    return item*item;
});
var arr3 = Array.from([1,2,3], (item) => item*item);

console.log(arr1); //[ 1, 4, 9 ]
console.log(arr2); //[ 1, 4, 9 ]
console.log(arr3); //[ 1, 4, 9 ]

值得提醒的是,擴展運算符(...)也能夠將某些數據結構轉爲數組。瀏覽器

// arguments 對象  
function foo() {  
  var args = [...arguments];  
}  
// NodeList 對象  
[...document.querySelectorAll('div')]  

2. Array.of()

Array.of方法用於將一組值,轉換爲數組。Array.of老是返回參數值組成的數組。若是沒有參數,就返回一個空數組。數據結構

Array.of基本上能夠用來替代Array()或new Array(),而且不存在因爲參數不一樣而致使的重載。它的行爲很是統一。ecmascript

這個方法的主要目的,是彌補數組構造函數Array()的不足。由於參數個數的不一樣,會致使Array()的行爲有差別函數

Array() // []  
Array(3) // [, , ,]  
Array(3, 11, 8) // [3, 11, 8]  
  
Array.of() // []  
Array.of(3) // [3]  
Array.of(3, 11, 8) // [3,11,8]  
  
Array.of(3).length // 1   
Array.of(undefined) // [undefined]  
Array.of(1) // [1]  
Array.of(1, 2) // [1, 2]  

Array.of方法能夠用下面的代碼模擬實現:this

function ArrayOf(){
  return [].slice.call(arguments);
}

 3. find() 和 findIndex()

數組實例的find方法,用於找出第一個符合條件的數組成員。它的參數是一個回調函數,全部數組成員依次執行該回調函數,直到找出第一個返回值爲true的成員,而後返回該成員。若是沒有符合條件的成員,則返回undefined。spa

[1, 4, -5, 10].find((n) => n < 0)  
// -5  
[1, 5, 10, 15].find(function(value, index, arr) {  
    return value > 9;  
}) // 10  

  上面代碼中,find方法的回調函數能夠接受三個參數,依次爲當前的值、當前的位置和原數組
數組實例的findIndex方法的用法與find方法很是相似,返回第一個符合條件的數組成員的位置,若是全部成員都不符合條件,則返回-1。.net

[1, 5, 10, 15].findIndex(function(value, index, arr) {  
    return value > 9;  
}) // 2  

這兩個方法均可以接受第二個參數,用來綁定回調函數的this對象
另外,這兩個方法均可以發現NaN,彌補了數組的IndexOf方法的不足。

[NaN].indexOf(NaN)  
// -1  
[NaN].findIndex(y => Object.is(NaN, y))  
// 0  

4. fill()

fill()方法使用給定值,填充一個數組。

['a', 'b', 'c'].fill(7)  
// [7, 7, 7]  
new Array(3).fill(7)  
// [7, 7, 7]  
['a', 'b', 'c'].fill(7, 1, 2)  
// ['a', 7, 'c']  

  上面代碼代表,fill方法用於空數組的初始化很是方便。數組中已有的元素,會被所有抹去。
fill()方法還能夠接受第二個和第三個參數,用於指定填充的起始位置和結束位置

['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']

5. entries() , keys() 和 values()

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']  

6. includes()

ES5中,咱們經常使用數組的indexOf方法,檢查是否包含某個值。indexOf方法有兩個缺點,一是不夠語義化,它的含義是找到參數值的第一個出現位置,因此要去比較是否不等於 -1 ,表達起來不夠直觀。二是,它內部使用嚴格至關運算符( === )進行判斷,這會致使對NaN的誤判。

[NaN].indexOf(NaN)  
// -1  
includes使用的是不同的判斷算法,就沒有這個問題。  
[NaN].includes(NaN)  
// true 

Array.prototype.includes方法返回一個布爾值,表示某個數組是否包含給定的值,與字符串的includes方法相似。該方法屬於 ES7 ,但 Babel 轉碼器已經支持。

[1, 2, 3].includes(2); // true  
[1, 2, 3].includes(4); // false  
[1, 2, NaN].includes(NaN); // true  

該方法的第二個參數表示搜索的起始位置,默認爲 0 。若是第二個參數爲負數,則表示倒數的位置,若是這時它大於數組長度(好比第二個參數爲 -4 ,但數組長度爲 3 ),則會重置爲從 0 開始。

[1, 2, 3].includes(3, 3); // false  
[1, 2, 3].includes(3, -1); // true  

下面代碼用來檢查當前環境是否支持該方法,若是不支持,部署一個簡易的替代版本。

const contains = (() =>  
Array.prototype.includes  
    ? (arr, value) => arr.includes(value)  
    : (arr, value) => arr.some(el => el === value)  
)();  

contains(["foo", "bar"], "baz"); // => false  

另外, Map 和 Set 數據結構有一個has方法,須要注意與includes區分。
Map 結構的has方法,是用來查找鍵名的,好比Map.prototype.has(key)、WeakMap.prototype.has(key)、Reflect.has(target, propertyKey)。
Set 結構的has方法,是用來查找的,好比Set.prototype.has(value)、WeakSet.prototype.has(value)。

7. 數組的空位

數組的空位指,數組的某一個位置沒有任何值。好比,Array構造函數返回的數組都是空位。

注意,空位不是undefined,一個位置的值等於undefined,依然是有值的。空位是沒有任何值,in運算符能夠說明這一點。

0 in [undefined, undefined, undefined] // true
0 in [, , ,] // false

  上面代碼說明,第一個數組的 0 號位置是有值的,第二個數組的 0 號位置沒有值。

ES5 對空位的處理,已經很不一致了,大多數狀況下會忽略空位。
  forEach() ,  filter() ,  every() 和some()都會跳過空位。
  map()會跳過空位,但會保留這個值
  join()和toString()會將空位視爲undefined,而undefined和null會被處理成空字符串。

// forEach方法
[,'a'].forEach((x,i) => console.log(i)); // 1

// filter方法
['a',,'b'].filter(x => true) // ['a','b']

// every方法
[,'a'].every(x => x==='a') // true

// some方法
[,'a'].some(x => x !== 'a') // false

// map方法
[,'a'].map(x => 1) // [,1]

// join方法
[,'a',undefined,null].join('#') // "#a##"

// toString方法
[,'a',undefined,null].toString() // ",a,,"

ES6則是明確將空位轉爲undefined。

//Array.from方法會將數組的空位,轉爲undefined,也就是說,這個方法不會忽略空位。  
Array.from(['a',,'b'])  // [ "a", undefined, "b" ]  

//擴展運算符(...)也會將空位轉爲undefined。  
[...['a',,'b']]  // [ "a", undefined, "b" ]  

//copyWithin()會連空位一塊兒拷貝。  
[,'a','b',,].copyWithin(2,0) // [,"a",,"a"]  

//fill()會將空位視爲正常的數組位置。  
new Array(3).fill('a') // ["a","a","a"]  

//for...of循環也會遍歷空位。  
let arr = [, ,];  
for (let i of arr) {  
    console.log(1);  
}  
// 1  
// 1  
//上面代碼中,數組arr有兩個空位,for...of並無忽略它們。若是改爲map方法遍歷,空位是會跳過的。  

//
entries()、keys()、values()、find()和findIndex()會將空位處理成undefined。 // entries() [...[,'a'].entries()] // [[0,undefined], [1,"a"]] // keys() [...[,'a'].keys()] // [0,1] // values() [...[,'a'].values()] // [undefined,"a"] // find() [,'a'].find(x => true) // undefined // findIndex() [,'a'].findIndex(x => true) // 0 //因爲空位的處理規則很是不統一,因此建議避免出現空位。

 

參考: w3cschool—數組的拓展

相關文章
相關標籤/搜索