ES6新增數(shù)組遍歷方法

定義一個(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é):

  1. forEach、map、filter都可以遍歷數(shù)組
  2. forEach操作的原數(shù)組,map、filter會(huì)返回一個(gè)新的數(shù)組
  3. 純粹的遍歷操作使用forEach,如果想得到原數(shù)組的克隆使用map,如果想根據(jù)條件篩選使用filter
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容