javescript經驗文檔(循環語句篇)

循環語句


通常for循環

{
    let array = [1,2,3,4,5,6,7];  
    for (let i = 0; i < array.length; i++) {  
        console.log(i,array[i]);  
    }
}

forEach方法

{
    let array = ['aa','abc','ccr',154,'s1'];
    array.forEach(v=>{  //es6
        console.log(v);  
    });
    array.forEach(function(v){  //es5
        console.log(v);  
    });
}

注意:在使用forEach遍歷數組以前必定要判斷數組是否已經定義!es6

用for in的方法

遍歷數組

{
    let array = ['aa','abc','ccr',154,'s1'];
    for(let index in array) {  
        
        console.log(index,array[index]);  
    };    
}

對enumerable對象操做

{
    let A = {a:1,b:2,c:3,d:"hello world"};  
    for(let key in A) {
        //key 爲對象的鍵
        console.log(k,A[k]);  
    } 
}

用for of的方法

{
    let array = ['aa','abc','ccr',154,'s1'];
    for(let v of array) {  
        console.log(v);  
    }; 
    let s = "helloabc"; 
    for(let c of s) {  
        console.log(c); 
    }
}

總結來講:for in老是獲得對像的key或數組,字符串的下標,而for of和forEach同樣,是直接獲得值。因此,for of不能對象用數組

while 循環

{
    let i = 0, x = '';
    while (i<5) {
        console.log("The number is " + i + "<br>");
        i++;
    }
}

do/while 循環

{
    let i = 0, x = '';
    do {
        console.log("The number is " + i + "<br>");
        i++;
    }
    while (i<5);
}
相關文章
相關標籤/搜索