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);
}
相关文章
相关标签/搜索