JavaScript遍历对象和数组

一、遍历对象(不包含继承属性)

var obj = {'a':'a','b':'b','c':'c'};

Object.keys(obj).forEach(function(key){

    console.log(key,":",obj[key]);

});

Object.getOwnPropertyNames(obj).forEach(function(key){

    console.log(key,":",obj[key]);

});

Reflect.ownKeys(obj).forEach(function(key){

console.log(key,":",obj[key]);

});

二、遍历数组

forEach

var arr=[1,2,3,4];

arr.forEach(function(val, index) {

console.log(index, ":",val);

});

for in

var arr=["张三","李四","王五","赵六"];

for (var index in arr){

console.log(index,":",arr[index]);

}

你可能感兴趣的:(JavaScript遍历对象和数组)