如何循环遍历 Node.js 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41677815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through Node.js array
提问by jpsstack
How can I display the variables of the array?
如何显示数组的变量?
Code:
代码:
console.log(rooms);
for (var i in rooms) {
console.log(i);
}
Output:
输出:
{ rooms:
[ { room: 'Raum 1', persons: 1 },
{ room: 'R2', persons: 2 },
{ room: 'R3', persons: 3 } ] }
rooms
回答by Alister
回答by ScottyG
Using forEach()with your code example (room is an object) would look this:
将forEach()与您的代码示例(房间是一个对象)一起使用将如下所示:
temp1.rooms.forEach(function(element)
{
console.log(element)
});
Using For ofwith your code sample (if we wanted to return the rooms) looks like:
使用For of与您的代码示例(如果我们想返回房间)看起来像:
for(let val of rooms.room)
{
console.log(val.room);
}
Note: notable difference between For of and forEach, is For of supports breaking and forEach has no way to break for stop looping (without throwing an error).
注意:For of 和 forEach 之间的显着区别是 For of 支持中断,而 forEach 无法中断 for stop 循环(不会引发错误)。
回答by Dominic
for (var i in rooms) {
console.log(rooms[i]);
}
Note it's good practice to do a hasOwnPropertycheck with inand it is for objects. So you're better off with for...ofor forEach.
请注意,对对象进行hasOwnProperty检查in是一种很好的做法。所以你最好使用for...ofor forEach。

