for循環(huán)
const ary = [10, 20, 30];
for(let i = 0, len = ary.length; i < len; i++) {
console.log(ary[i]);
}
// 10
// 20
// 30
for...in循環(huán)
此語句以任意順序遍歷一個對象的可枚舉屬性郊艘。
const person = {
firstName: "Jon",
age:18
};
for(let info in person) {
console.log(`person[${info}] = ${person[info]}`);
}
//person[firstName] = Jon
//person[age] = 18
注意:
for...in只能遍歷對象的“可枚舉的屬性”
for-in遍歷屬性的順序并不確定,因此數(shù)組迭代推薦使用for循環(huán)(或者使用 Array.prototype.forEach() 或 for...of 循環(huán))
Array.prototype.forEach()
在ES5中引入了新的數(shù)組循環(huán)forEach對數(shù)組中的每個元素執(zhí)行一次提供的函數(shù)唯咬。
該方法按升序?yàn)閿?shù)組中含有效值的每一項(xiàng)執(zhí)行一次callback 函數(shù)纱注,那些已刪除(使用delete方法等情況)或者未初始化的項(xiàng)將被跳過(但不包括那些值為 undefined 的項(xiàng))。
function logArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
}
// 注意索引2被跳過了胆胰,因?yàn)樵跀?shù)組的這個位置沒有項(xiàng)
[2, 5, ,9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[3] = 9
[2, 5,"" ,9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] =
// a[3] = 9
[2, 5, undefined ,9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = undefined
// a[3] = 9
let xxx;
// undefined
[2, 5, xxx ,9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = undefined
// a[3] = 9
Tips:forEach第二個參數(shù)是可選參數(shù)狞贱,替代回調(diào)函數(shù)中的this值。
for...of語句
let iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31
注意:
跟Array.prototype.forEach()相比蜀涨,for...of可以正確響應(yīng)break, continue, return瞎嬉,throw。
for...of不僅可迭代數(shù)組厚柳,還支持大多數(shù)類數(shù)組對象氧枣,例如DOM nodelist對象。還有其它可迭代對象(包括Map别垮,Set便监,String,TypedArray碳想,arguments對象等等)
for...of不支持普通對象烧董,但如果你想迭代一個對象的屬性毁靶,你還是用for-in循環(huán)吧