JS 中for迴圈 、 for-of 、forEach 、for-in的區別
阿新 • • 發佈:2021-11-19
一、幾種遍歷的用法:
1、一般的遍歷陣列的方法:
var array = [1,2,3,4,5,6,7];
for (var i = 0; i < array.length; i++) {
console.log(i,array[i]);
}
2、用for in的方遍歷陣列,得到的是索引
var array = [1,2,3,4,5,6,7];
for(let index in array) {
console.log(index,array[index]);
};
3、forEach,得到的是元素,只能用於陣列
var array = [1,2,3,4,5,6,7]; array.forEach(e=>{ console.log(e); }); array.forEach(function(e){ console.log(e); });
4、用for in不僅可以對陣列,也可以對enumerable物件操作!得到的是索引
var table = {
a : 10,
b : true,
c : "jadeshu"
};
for(let index in table) {
console.log(index, table[index]);
}
5、在ES6中,增加了一個for of迴圈,得到的是元素,不能物件用
var array = [1,2,3,4,5,6,7]; for(let ele of array) { console.log(ele); }; var str = "helloabc"; for(let ele of str) { console.log(ele); }
二、效能比較
從效能上看:for迴圈 > for-of > forEach > for-in