2016-11-04 75 views
5
var points = [{ x: 75, y: 25},{ x: 75+0.0046, y: 25}]; 

我将如何遍历这个。 我想先打印x和y值,然后打印第二个和第二个...如何迭代JavaScript中的数组和对象

+0

可能重复:http://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties – Rajesh

回答

5

使用Array#forEach数组迭代的方法。

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

 
points.forEach(function(obj) { 
 
    console.log(obj.x, obj.y); 
 
})

+0

如果我想将数据存储在某些var中,而不是.var X = obj.x; \t \t var Y = obj.y;这可以做或不做,因为新的js; –

+0

@gauravsingh这将只给你最后一个值,因为你正在循环中赋值。请解释你正在努力达到的目标,然后我们会帮助你更容易。此外,下次请参考您在提问时得到的建议 – Rajesh

2

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

我比搜索重复项更快地键入答案,并将其标记为原样。 –

+0

我必须说,你有一些打字速度,但它更好地保持**我们的门户**干净。另外请记住,旧帖子有更多答案覆盖更多选项,因此如果您标记为重复,那么搜索它的人将帮助他学习更多 – Rajesh