js遍历数组和遍历对象属性

遍历对象

let json = {
            key1:"hello",
            key2:"world"
        }

        //最简洁方法
        for(let key in json){
            console.log(key,":",json[key]);
        }
        
        //转成数组再遍历
        Object.keys(json).forEach( key => console.log(key,":",json[key]));
/**
* 都输出:
key1 : hello
key2 : world
*/

遍历数组

let arr = ["hello","world"];
//for...in
        for(let key in arr){
            console.log(arr[key]);
        }
//for...of
        for(var item of arr) {
            console.log(item);
        }
//for
        for(var i = 0; i < arr.length; i++){
            console.log(arr[i]);
        }
//forEach
        arr.forEach(function(item,index,self){
            console.log(item);
        })
/**
* 都输出:
hello
world
*/
 
     

遍历对象和遍历数组都可用for...in循环

猜你喜欢

转载自blog.csdn.net/SE_JW/article/details/129335909