-
for語句想幻,while語句蒸痹,do...while語句
-
for-in循環(huán)
for...in循環(huán)只能獲取鍵名不能獲取鍵值;
for...in循環(huán)是以字符串作為鍵名(數(shù)組的鍵名是數(shù)字);
for...in循環(huán)不僅遍歷數(shù)字鍵名,還會遍歷手動添加的其他鍵这揣;
因此,for...in循環(huán)主要為遍歷對象而設(shè)計的影斑,不適用于遍歷數(shù)據(jù)
/* for...in循環(huán)只能獲取對象的鍵名给赞,不能直接獲取鍵值 */
let obj = {a: 1, b: 2, c: 3};
for (let i in obj) {
console.log(i); // a b c
}
/* for...in循環(huán)是以字符串作為鍵名 */
const arr = [1, 2, 3];
for (let i in arr) {
console.log(typeof i); //string
}
/* for...in循環(huán)不僅遍歷數(shù)字鍵名,還會遍歷手動添加的其他鍵 */
let arr = [3, 5, 7];
arr.foo = 'hello';
for (let i in arr) {
console.log(i); // "0", "1", "2", "foo"
}
-
for-of循環(huán)
ES6引入的一個循環(huán)矫户,作為遍歷所有數(shù)據(jù)結(jié)構(gòu)的統(tǒng)一方法片迅;
一個數(shù)據(jù)結(jié)構(gòu)只要部署了Symbol.iterator屬性,就被視為具有iterator接口皆辽,就可以用for...of循環(huán)遍歷它的成員柑蛇;
使用范圍包括數(shù)組,Set和Map結(jié)構(gòu)膳汪,字符串,類數(shù)組對象(DOM集合)等九秀;但是普通對象并不適用遗嗽。
for...of循環(huán)返回的是鍵值;
for...of循環(huán)可以與break鼓蜒、continue和return配合使用
/* 數(shù)組原生具備interator接口痹换,及默認(rèn)部署了Symbol.iterator屬性 */
let arr = [10, 20, 30];
for (let v of arr) {
v += 1;
console.log(v); // 11 21 31
}
/* 類數(shù)組的循環(huán)(字符串) */
let str = 'hello';
for (let v of str) {
console.log(v); // h e l l o
}
/* 不是說所有的類數(shù)組對象都具有interator接口,簡單的解決方法就是用Array,form方法將其轉(zhuǎn)為數(shù)組 */
let arrayLike = { length: 2, 0: 'a', 1: 'b' };
for (let x of Array.from(arrayLike)) {
console.log(x);// a b
}
/* 與break都弹、continue和return配合退出循環(huán) */
for (var n of fibonacci) {
if (n > 1000)
break;
console.log(n);
}
-
forEach
對數(shù)組進行遍歷娇豫,當(dāng)遇到數(shù)組的空位時會跳過。
forEach不能退出循環(huán)
[1, 2, , 4].forEach(v => {
conosle.log(v); //1 2 4
});