zoukankan      html  css  js  c++  java
  • js数组遍历和对象遍历小结

    数组的遍历

    • for循环
    for(var j = 0,len = arr.length; j < len; j++){
        console.log(arr[j]);
    }
    • forEach,性能比for还弱
    arr.forEach(function(value,i){
        console.log('forEach遍历:'+i+'--'+value);
    })
    • map遍历
    arr.map(function(value,index){
        console.log('map遍历:'+index+'--'+value);
    });
    • for-of遍历 是ES6新增功能
    for( let i of arr){
        console.log(i);
    }

    forEachmap是ECMA5新增数组的方法,for-of是ES6新增方法,ie9以下的浏览器还不支持

    对象遍历

    • for in
    for(var key in obj){
        console.log(key+": "+obj[key])
    }
    • forEach
    obj.forEach((value,index)=>{
        console.log(value+","+index)
    })

    补充

    • for-of
        // for-of遍历数组,不带索引,i即为数组元素
        for(let i of arrTmp){
            console.log(i)
        }
        //输出 "value1" "value2" "value3"
    
        // for-of遍历Map对象
        let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
        for (let [key, value] of iterable) {
          console.log(value);
        }
        //输出 1 2 3
    
        // for-of遍历字符串
        let iterable = "china中国";
        for (let value of iterable) {
          console.log(value);
        }
        //输出 "c" "h" "i" "n" "a" "中" "国"
    • Object.keys()返回键名数组
        //数组类型
        let arr = ["a", "b", "c"];
        console.log(Object.keys(arr));
        // (3) ['0', '1', '2']
    
        // 类数组对象
        let anObj = { 100: 'a', 2: 'b', 7: 'c' };
        console.log(Object.keys(anObj));
        // (3) ['2', '7', '100']
    
        //一般对象
        let xyz = {z: "zzz", x: "xxx", y: "yyy"};
        console.log(Object.keys(xyz));
        // (3) ["z", "x", "y"]
  • 相关阅读:
    Educational Codeforces Round 22 C. The Tag Game
    Codeforces Round #421 (Div. 1) B. Mister B and PR Shifts(技巧)
    Codeforces Round #422 (Div. 2) D. My pretty girl Noora
    Codeforces Round #422 (Div. 2) C. Hacker, pack your bags!
    hdu3756(三分)
    hihocoder1496(高维前缀和)
    AOJ731(不等式)
    UVALive7042(博弈论)
    Codeforces 284E(概率)
    hdu4778(状态压缩dp)
  • 原文地址:https://www.cnblogs.com/conglvse/p/9596347.html
Copyright © 2011-2022 走看看