1. Array.from()
Array.from方法用于將兩類對象轉為真正的數組:類似數組的對象(array- like object)和可遍歷(iterable)的對象(包括ES6新增的數據結構Set和Map)
let obj = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// ES5的寫法
var arr1 = [].slice.call(obj); // ['a', 'b', 'c']
// ES6的寫法
let arr2 = Array.from(obj); // ['a', 'b', 'c']
2.Array.of()
Array.of方法用于將一組值,轉換為數組。
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
3. 數組實例的 copyWithin()
數組實例的copyWithin方法,在當前數組內部,將指定位置的成員復制到其他位置(會覆蓋原有成員),然后返回當前數組。也就是說,使用這個方法,會修改當前數組。
Array.prototype.copyWithin(target, start = 0, end = this.length)
target(必需):從該位置開始替換數據。
start(可選):從該位置開始讀取數據,默認為0。如果為負值,表示倒數。
-
end(可選):到該位置前停止讀取數據,默認等于數組長度。如果為負值,表示倒數。
// 將3號位復制到0號位 [1, 2, 3, 4, 5].copyWithin(0, 3, 4) // [4, 2, 3, 4, 5] // -2相當于3號位,-1相當于4號位 [1, 2, 3, 4, 5].copyWithin(0, -2, -1) // [4, 2, 3, 4, 5] // 將3號位復制到0號位 [].copyWithin.call({length: 5, 3: 1}, 0, 3) // {0: 1, 3: 1, length: 5} // 將2號位到數組結束,復制到0號位 var i32a = new Int32Array([1, 2, 3, 4, 5]); i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, 5] // 對于沒有部署 TypedArray 的 copyWithin 方法的平臺 // 需要采用下面的寫法 [].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); // Int32Array [4, 2, 3, 4, 5]
4. 數組實例的 find() 和 findIndex()
數組實例的find方法,用于找出第一個符合條件的數組成員。它的參數是一個回調函數,所有數組成員依次執行該回調函數,直到找出第一個返回值為true的成員,然后返回該成員。如果沒有符合條件的成員,則返回undefined。
[1, 4, -5, 10].find((n) => n < 0)
// -5
[1, 5, 10, 15].find(function(value, index, arr) {
return value > 9;
}) // 10
數組實例的findIndex方法的用法與find方法非常類似,返回第一個符合條件的數組成員的位置,如果所有成員都不符合條件,則返回-1
[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value > 9;
}) // 2
5.數組實例的fill()
fill方法使用給定值,填充一個數組。
['a', 'b', 'c'].fill(7)
// [7, 7, 7]
new Array(3).fill(7)
// [7, 7, 7]
fill方法還可以接受第二個和第三個參數,用于指定填充的起始位置和結束位置
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
上面代碼表示,fill方法從1號位開始,向原數組填充7,到2號位之前結束
6.數組實例的 entries(),keys() 和 values()
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"
7. 數組實例的 includes()
Array.prototype.includes方法返回一個布爾值,表示某個數組是否包含給定的值,與字符串的includes方法類似
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, NaN].includes(NaN) // true
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)。