定義一個(gè)數(shù)組
var testArray=[100,20,50,46,80,95];
forEach() 方法: 循環(huán)原來的數(shù)組
語法:arr.forEach(function(value,index){ //回調(diào)函數(shù)體 }) ES5
語法:arr.forEach((value,index)=>{ //回調(diào)函數(shù)體 }) ES6
參數(shù)說明: value表示數(shù)組的元素,index表示數(shù)組的索引
testArray.forEach((v,i)=>{
console.log("索引",i,"元素",v);
});
map() 方法: 循環(huán)原數(shù)組并映射一個(gè)新數(shù)組出來
映射:源和目標(biāo)一一對(duì)應(yīng)的方式
語法:arr.map((value,index)=>{ //回調(diào)函數(shù)體 })
-------------map() 基本使用---------------
testArray.map((v,i)=>{
console.log("索引",i,"元素",v);
});
console.log("原數(shù)組",testArray,"新數(shù)組",newArray);
-------------map() 高級(jí)使用---------------
var new2Array=testArray.map((v,i)=>{
if(v>=90){
return v;
}
});
console.log("原數(shù)組",testArray,"新數(shù)組1",newArray,"新數(shù)組2",new2Array);
//修改新的數(shù)組
new2Array.push(50,60);
for (let o of new2Array) {
if(o!=undefined){
console.log(o);
}
}
filter() 方法: 過濾不需要的數(shù)組元素
語法:arr.filter((value,index)=>{ //回調(diào)函數(shù)體 })
testArray=[100,20,50,46,80,95];
var betterArray=testArray.filter((v,i)=>{
if(v>=80){
return v;
}
});
console.log("分?jǐn)?shù)大于等于80分",betterArray);
betterArray.push(85,99);
console.log("分?jǐn)?shù)大于等于80分",betterArray);
console.log("原數(shù)組",testArray);
總結(jié):
- forEach、map、filter都可以遍歷數(shù)組
- forEach操作的原數(shù)組,map、filter會(huì)返回一個(gè)新的數(shù)組
- 純粹的遍歷操作使用forEach,如果想得到原數(shù)組的克隆使用map,如果想根據(jù)條件篩選使用filter