for、for...in、for...of、forEach和map的區別

前端晉級攻城獅發表於2019-05-28

遍歷陣列 //for…in遍歷屬性名稱key,for…of遍歷屬性值value

for(let i in arr){
      console.log(i)   //0,1,2    索引值
 }
 for(let item of arr){
     console.log(item )   //a,b,c     es6的語法
 }
複製程式碼
var arr=[10,20,30];
 var newArr1=arr.forEach(function(value,index,array){
 //value為遍歷的當前元素,index為當前索引,array為正在操作的陣列
     return value*2
})
console.log(newArr1);   //undefined     forEach沒有返回值
console.log(arr);   //[10,20,30]      原陣列

 var newArr2=arr.map(function(value,index,array){
 //value為遍歷的當前元素,index為當前索引,array為正在操作的陣列
     return value*2
})
console.log(newArr2);   //[20,40,60]    map有返回值
console.log(arr);   //[10,20,30]      仍然為原陣列

arr.map(function(value,index,array){
     array[index]=value*2;
})
console.log(arr);   //[20.40,60]    
//通過下標改變陣列的值, 這點和forEach相同
複製程式碼

遍歷物件

let obj={a:1,b:2}
for(let i in obj){
     console.log(i)   //a,b
}
for(let item of obj){     //不可用於遍歷物件
     console.log(item)       //TypeError
}
複製程式碼

Object.keys()和Object.values()來遍歷物件。它們都是返回陣列。

Object.keys(obj)      //[a,b]
Object.values(obj)    //[1,2]
複製程式碼

相關文章