js数组遍历和对象遍历小结

时间:2024-08-03 12:38:08

数组的遍历

  • 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"]