JavaScript遍历数组、对象

1. for...of(for of遍历的只是数组内的元素,而不包括数组的原型属性method和索引name)

Array.prototype.method=function(){
 console.log(this.length);
  }
var myArray=[1,2,4,5,6,7]
myArray.name="数组";
for (var value of myArray) {
  console.log(value); // 1,2,3,4,5,6,7
  }
for in遍历的是数组的索引(即键名),而for of遍历的是数组元素值。

2. for...in(用for in来遍历对象的键名)

  • for-in语句是一中精准的迭代语句,用于枚举对象的属性
  • for(item in window) {} 遍历window对象的所有属性,每次执行循环都会将window的一个属性赋值给变量item
  • for in 可以遍历到myObject的原型方法method,如果不想遍历原型方法和属性的话,可以在循环内部判断一下,hasOwnPropery方法可以判断某属性是否是该对象的实例属性
for (var key in myObject) {
  if(myObject.hasOwnProperty(key)){
     console.log(key);
  }
}
  • 同样可以通过ES5的Object.keys(myObject)获取对象的实例属性组成的数组,不包括原型方法和属性。
Object.prototype.method=function(){
  console.log(this);
}
var myObject={
  a:1,
  b:2,
  c:3
}
Object.keys(myObject).forEach(function(key,index){
   console.log(key,myObject[key])
})

3. forEach

  • forEach是ES5中Array新方法中最基本的一个
[].forEach(function(value, index, array) {
   // 数组元素,元素的索引,数组本身 , this == obj
},obj);

//兼容低版本IE
Array.prototype.forEach = Array.prototype.forEach || function(fn, context){
  for (var k = 0, length = this.length; k < length; k++) {
    if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, k)) {
      fn.call(context, this[k], k, this);
    }
  }
}

4. map

  • map方法的作用就是将原数组按照一定的规则映射成一个新的数组。再将其返回,是返回一个新的数组,而不是将原数组直接改变。
//需return值
var data=[1,3,4] 
var squares=data.map(function(val,index,arr){
      console.log(arr[index]==val);  // ==> true
      return val*val           
})
console.log(squares);  //[1,9,16]
//兼容低版本IE
Array.prototype.map = Array.prototype.map || function (fn, context) {
  var arr = [];
  if (typeof fn === "function") {
    for (var k = 0, length = this.length; k < length; k++) {      
      arr.push(fn.call(context, this[k], k, this));
    }
  }
  return arr;
};
原文地址:https://www.cnblogs.com/Lewiskycc/p/7040335.html