首页 > 技术文章 > 循环=>轮回=>js循环比拼

xiaomaotao 2019-10-19 17:20 原文


  for (var index = 0; index < myArray.length; index++) {
    console.log(myArray[index]);
  }

1 原生版forEach
  第一个参数value为遍历到的元素
  第二个参数index为遍历到的索引/下标
  注意:原生forEach只能遍历数组,不能遍历伪数组

  var diyArray = [1,2,3,4,5] diyArray.forEach(function(value,index){ console.log(index,value) })

 

  写法简单了许多,但也有短处:你不能中断循环(使用break语句或使用return语句。

  0  1

  1  2

  2  3

  3  4

  4  5

2 jQuery版each
  1.第一个参数为遍历的数组或者对象
  2.第二个参数为要处理的函数

 

  $(function(){ var diyArray = [1,2,3,4,5] $.each(diyArray,function(index,value){ console.log(index,value) }) })

  

  0  1

  1  2

  2  3

  3  4

  4  5

 

  
  同时也可以遍历伪数组

  

  $(function(){
    var weiArray = {
      0:1,
      1:2,
      2:3,
      3:4,
      length:4
    }
    $.each(weiArray,function(index,value){
      console.log(index,value)
    })
  })

3 for .... of

for...of语句可迭代对象(包括 ArrayMapSetStringTypedArrayarguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句

const array1 = ['a', 'b', 'c'];

for (const element of array1) {
console.log(element);
}

// expected output: "a"
// expected output: "b"
// expected output: "c"

4 for...in  for...in语句以任意顺序遍历一个对象的除Symbol以外的可枚举属性。

函数接受一个对象作为参数。被调用时迭代传入对象的所有可枚举属性然后返回一个所有属性名和其对应值的字符串。

var obj = {a:1, b:2, c:3};
    
for (var prop in obj) {
  console.log("obj." + prop + " = " + obj[prop]);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

下面的函数说明了hasOwnProperty()的用法:继承的属性不显示。

var triangle = {a: 1, b: 2, c: 3};

function ColoredTriangle() {
  this.color = 'red';
}

ColoredTriangle.prototype = triangle;

var obj = new ColoredTriangle();

for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    console.log(`obj.${prop} = ${obj[prop]}`);
  } 
}

// Output:
// "obj.color = red"

  

 

推荐阅读