1. Array.from()
Array.from方法用于將兩類對象轉(zhuǎn)為真正的數(shù)組:類似數(shù)組的對象(array- like object)和可遍歷(iterable)的對象(包括ES6新增的數(shù)據(jù)結(jié)構(gòu)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方法用于將一組值,轉(zhuǎn)換為數(shù)組。
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
3. 數(shù)組實例的 copyWithin()
數(shù)組實例的copyWithin方法烤宙,在當前數(shù)組內(nèi)部烹骨,將指定位置的成員復制到其他位置(會覆蓋原有成員)窜管,然后返回當前數(shù)組揩尸。也就是說宛渐,使用這個方法界斜,會修改當前數(shù)組仿耽。
Array.prototype.copyWithin(target, start = 0, end = this.length)
target(必需):從該位置開始替換數(shù)據(jù)。
start(可選):從該位置開始讀取數(shù)據(jù)各薇,默認為0项贺。如果為負值,表示倒數(shù)峭判。
-
end(可選):到該位置前停止讀取數(shù)據(jù)开缎,默認等于數(shù)組長度。如果為負值林螃,表示倒數(shù)奕删。
// 將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號位到數(shù)組結(jié)束疗认,復制到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. 數(shù)組實例的 find() 和 findIndex()
數(shù)組實例的find方法完残,用于找出第一個符合條件的數(shù)組成員。它的參數(shù)是一個回調(diào)函數(shù)横漏,所有數(shù)組成員依次執(zhí)行該回調(diào)函數(shù)谨设,直到找出第一個返回值為true的成員,然后返回該成員绊茧。如果沒有符合條件的成員铝宵,則返回undefined。
[1, 4, -5, 10].find((n) => n < 0)
// -5
[1, 5, 10, 15].find(function(value, index, arr) {
return value > 9;
}) // 10
數(shù)組實例的findIndex方法的用法與find方法非常類似,返回第一個符合條件的數(shù)組成員的位置鹏秋,如果所有成員都不符合條件尊蚁,則返回-1
[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value > 9;
}) // 2
5.數(shù)組實例的fill()
fill方法使用給定值,填充一個數(shù)組侣夷。
['a', 'b', 'c'].fill(7)
// [7, 7, 7]
new Array(3).fill(7)
// [7, 7, 7]
fill方法還可以接受第二個和第三個參數(shù)横朋,用于指定填充的起始位置和結(jié)束位置
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
上面代碼表示,fill方法從1號位開始百拓,向原數(shù)組填充7琴锭,到2號位之前結(jié)束
6.數(shù)組實例的 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. 數(shù)組實例的 includes()
Array.prototype.includes方法返回一個布爾值衙传,表示某個數(shù)組是否包含給定的值决帖,與字符串的includes方法類似
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, NaN].includes(NaN) // true
Map 和 Set 數(shù)據(jù)結(jié)構(gòu)有一個has方法,需要注意與includes區(qū)分
- Map 結(jié)構(gòu)的has方法蓖捶,是用來查找鍵名的
- Map.prototype.has(key)地回、
- WeakMap.prototype.has(key)、
- Reflect.has(target, propertyKey)俊鱼。
- Set 結(jié)構(gòu)的has方法刻像,是用來查找值的
- Set.prototype.has(value)
- WeakSet.prototype.has(value)。