[JavaScript數(shù)組]一篇中介紹了ES6之前的數(shù)組方法艺智。本篇介紹一下ES6里新增的數(shù)組方法蚌吸。
- keys,values龄坪,entries
- find昭雌,findIndex,inclueds
- fill健田,copyWithin
- 靜態(tài)方法(from烛卧,of)
1. 數(shù)組實例的entries(),keys()和values()
三個方法都是用于遍歷數(shù)組。
- 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"
Array.map()
Array.map(function(ele){
console.log(ele) 打印每個數(shù)組中的數(shù)值
})
2. 數(shù)組實例的find() findIndex() includes()
find()
- find()方法用于找出第一個符合條件的數(shù)組成員好爬。它的參數(shù)是一個回調(diào)函數(shù)局雄,所有數(shù)組成員依次執(zhí)行該函數(shù),知道找出第一個返回true的成員存炮,然后返回該成員炬搭。沒有符合則返回undefined。
[1,4,-5,10].find((n) => n < 0);
//-5
- find方法接受三個參數(shù)穆桂,依次為當(dāng)前的值宫盔、當(dāng)前的位置和原數(shù)組
[1,5,10,15].find (function (value, index, arr) {
return value > 9;
}) //10
findIndex()
- findIndex()方法與find()類似,無符合條件返回-1.
這兩個方法都可接受第二個參數(shù)充尉,用來綁定回調(diào)函數(shù)的this對象飘言。
includes()
- 該方法返回一個布爾值,表示某個數(shù)組是否包含給定的值驼侠。
- 該方法的第二個參數(shù)表示搜索的起始位置,默認(rèn)為0.如果第二個參數(shù)是負(fù)數(shù)谆吴,則表示倒數(shù)位置倒源。如果倒數(shù)的絕對值大于數(shù)組長度,則會重置從0開始句狼。
第一個參數(shù)是查找的元素笋熬。
第二個參數(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ù)組實例的copyWithin() fill()
數(shù)組實例的copyWithin() 復(fù)制
在當(dāng)前數(shù)組內(nèi)部糖耸,將制定位置的成員復(fù)制到其他位置(會覆蓋原有成員)秘遏,然后返回當(dāng)前數(shù)組。
- 它接受三個參數(shù)嘉竟。三個參數(shù)都應(yīng)該是數(shù)值邦危,如不是,則自動轉(zhuǎn)為數(shù)值舍扰。
target(必需):從該位置開始替換數(shù)據(jù)倦蚪。
start(可選):從該位置開始讀取數(shù)據(jù),默認(rèn)為0.如果為負(fù)數(shù)边苹,表示倒數(shù)陵且。
end(可選):到該位置前停止讀取數(shù)據(jù),默認(rèn)等于數(shù)組長度个束。如果為負(fù)數(shù)滩报,表示倒數(shù)。
[1,2,3,4,5].copyWithin(0,3)
//[4,5,3,4,5]
數(shù)組實例的fill() 填充
- fill方法使用給定值播急,填充一個數(shù)組脓钾。
['a','b','c'].fill(7) //[7,7,7]
- fill方法接受第二個和第三個參數(shù),用于指定填充的起始位置和結(jié)束位置桩警。
['a','b','c'].fill(8,1,2) //['a',8,'c']
4. Array.from() Array.of()
Array.from()
用于將兩類對象轉(zhuǎn)為真正的數(shù)組可训。
- 類似數(shù)組的對象(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對象捶枢。
//NodeList對象
let ps = document.querySelectorAll('p');
Array.from(ps).forEach(function (p)) {
console.log(p);
});
//arguments對象
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ù)組的某一個位置沒有任何職烂叔。
Array(3) //[ , , ]
0 in [undefined, undefined, undefined] //true
0 in [ , , ,] //false