如何在JavaScript中遍历数组和对象

44
var points = [{ x: 75, y: 25},{ x: 75+0.0046, y: 25}];

我该如何迭代这个东西。 我想先打印x和y的值,然后是第二个值等等....


可能重复:https://dev59.com/IWQn5IYBdhLWcg3wtpBW - Rajesh
3个回答

14

使用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 X=obj.x; var Y=obj.y; 因为我是js的新手,所以不确定是否可行。 - gaurav singh
@gauravsingh 这会给你最后一个值,因为你在循环中分配值。请解释一下你想要实现什么,这样我们就更容易帮助你。另外,下次提问时,请参考您获得的建议。 - Rajesh

4

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) )


1
这是一个非常基础的问题,已经被回答了几次。你应该将其标记为重复。 - Rajesh

2
您可以使用 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);
}


1
我打出了答案,比查找重复并标记它要快。 - Rax Weber
我必须说你的打字速度很快,但最好保持我们的门户网站干净。还要记住,旧帖子有更多的答案涵盖更多的选项,所以如果你标记为重复,那么搜索它的人将会学到更多。 - Rajesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接