How to iterate over arrays and objects in JavaScript

This question already has an answer here:

  • For-each over an array in JavaScript? 23 answers

  • 使用Array#forEach方法进行数组迭代。

    var points = [{
      x: 75,
      y: 25
    }, {
      x: 75 + 0.0046,
      y: 25
    }];
    
    points.forEach(function(obj) {
      console.log(obj.x, obj.y);
    })

    var points = [{ x: 75, y: 25},{ x: 75+0.0046, y: 25}];
    
    //ES5
    points.forEach(function(point){ console.log("x: " + point.x + " y: " + point.y) })
    
    
    //ES6
    points.forEach(point=> console.log("x: " + point.x + " y: " + point.y) )

    你可以使用for..of循环。

    var points = [{ x: 75, y: 25},{ x: 75+0.0046, y: 25}];
    for (let point of points) {
        console.log(point.x, point.y);
    }
    链接地址: http://www.djcxy.com/p/12056.html

    上一篇: 通过JavaScript对象循环的最佳实践

    下一篇: 如何在JavaScript中迭代数组和对象