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遍历数组之前一定要判断数组是否已经定义!

用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);
}
阅读 640

推荐阅读

node(express/koa/egg)、MongoDB/mysql/sqlserve/oracle/postgresql、vue(vuex+vue-router+element/a...

7 人关注
44 篇文章
专栏主页