[JavaScript數(shù)組]一篇中介紹了ES6之前的數(shù)組方法。本篇介紹一下ES6里新增的數(shù)組方法。
- keys,values,entries
- find,findIndex,inclueds
- fill,copyWithin
- 靜態(tài)方法(from,of)
1. 數(shù)組實(shí)例的entries(),keys()和values()
三個(gè)方法都是用于遍歷數(shù)組。
- keys遍歷鍵名。
- values遍歷鍵值。
- entries遍歷鍵值對(duì)。
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"
Array.map()
Array.map(function(ele){
console.log(ele) 打印每個(gè)數(shù)組中的數(shù)值
})
2. 數(shù)組實(shí)例的find() findIndex() includes()
find()
- find()方法用于找出第一個(gè)符合條件的數(shù)組成員。它的參數(shù)是一個(gè)回調(diào)函數(shù),所有數(shù)組成員依次執(zhí)行該函數(shù),知道找出第一個(gè)返回true的成員,然后返回該成員。沒有符合則返回undefined。
[1,4,-5,10].find((n) => n < 0);
//-5
- find方法接受三個(gè)參數(shù),依次為當(dāng)前的值、當(dāng)前的位置和原數(shù)組
[1,5,10,15].find (function (value, index, arr) {
return value > 9;
}) //10
findIndex()
- findIndex()方法與find()類似,無(wú)符合條件返回-1.
這兩個(gè)方法都可接受第二個(gè)參數(shù),用來(lái)綁定回調(diào)函數(shù)的this對(duì)象。
includes()
- 該方法返回一個(gè)布爾值,表示某個(gè)數(shù)組是否包含給定的值。
- 該方法的第二個(gè)參數(shù)表示搜索的起始位置,默認(rèn)為0.如果第二個(gè)參數(shù)是負(fù)數(shù),則表示倒數(shù)位置。如果倒數(shù)的絕對(duì)值大于數(shù)組長(zhǎng)度,則會(huì)重置從0開始。
第一個(gè)參數(shù)是查找的元素。
第二個(gè)參數(shù)可選,表示開始查找的位置,不指定的話默認(rèn)為0,指定為負(fù)數(shù),表示倒著數(shù)。
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
3. 數(shù)組實(shí)例的copyWithin() fill()
數(shù)組實(shí)例的copyWithin() 復(fù)制
在當(dāng)前數(shù)組內(nèi)部,將制定位置的成員復(fù)制到其他位置(會(huì)覆蓋原有成員),然后返回當(dāng)前數(shù)組。
- 它接受三個(gè)參數(shù)。三個(gè)參數(shù)都應(yīng)該是數(shù)值,如不是,則自動(dòng)轉(zhuǎn)為數(shù)值。
target(必需):從該位置開始替換數(shù)據(jù)。
start(可選):從該位置開始讀取數(shù)據(jù),默認(rèn)為0.如果為負(fù)數(shù),表示倒數(shù)。
end(可選):到該位置前停止讀取數(shù)據(jù),默認(rèn)等于數(shù)組長(zhǎng)度。如果為負(fù)數(shù),表示倒數(shù)。
[1,2,3,4,5].copyWithin(0,3)
//[4,5,3,4,5]
數(shù)組實(shí)例的fill() 填充
- fill方法使用給定值,填充一個(gè)數(shù)組。
['a','b','c'].fill(7) //[7,7,7]
- fill方法接受第二個(gè)和第三個(gè)參數(shù),用于指定填充的起始位置和結(jié)束位置。
['a','b','c'].fill(8,1,2) //['a',8,'c']
4. Array.from() Array.of()
Array.from()
用于將兩類對(duì)象轉(zhuǎn)為真正的數(shù)組。
- 類似數(shù)組的對(duì)象(array-like object)
let arrayLike = {
'0':'a',
'1':'b',
'2':'c',
length:3
} ;
let arr2 = Array.from(arrayLike); //['a','b','c']
- DOM操作返回的NodeList集合,以及函數(shù)內(nèi)部的arguments對(duì)象。
//NodeList對(duì)象
let ps = document.querySelectorAll('p');
Array.from(ps).forEach(function (p)) {
console.log(p);
});
//arguments對(duì)象
function foo() {
var args = Array.from(arguments);
}
Array.of()
Array.of()用于將一組值,轉(zhuǎn)換為數(shù)組。
Array.of(3,11,5); //[3,11,5]Array.of(2).length; //1
4. 數(shù)組的空位
- 指數(shù)組的某一個(gè)位置沒有任何職。
Array(3) //[ , , ]
0 in [undefined, undefined, undefined] //true
0 in [ , , ,] //false