javescript经验文档(循环语句篇)

发布时间:2019-08-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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) {  
        
        @H_664_126@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);
}

脚本宝典总结

以上是脚本宝典为你收集整理的javescript经验文档(循环语句篇)全部内容,希望文章能够帮你解决javescript经验文档(循环语句篇)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。