简体   繁体   English

javascript将forEach用于嵌套数组

[英]javascript using forEach for nested arrays

If I have a nested array as follows: 如果我有一个nested array ,如下所示:

var attendees={attendees :[{name: John},{name: Terry}]}

how do I loop through the names using the forEach function? 如何使用forEach函数遍历名称? I have tried: 我努力了:

attendees.forEach(function(attendees){
    console.log(attendees.name):
});

but it does not loop through the subarrays and just gives me: 但是它不会遍历子数组,而只是给我:

[{name: John},{name: Terry}]

Appreciate the help! 感谢帮助!

With another foreach when detects is an array: 与另一个foreach何时检测到数组:

attendees.forEach(function(attendee){
   if(attendee.isArray()) {
      attendee.forEach(function(subattendee) {
         console.log(subattendee):
      });
   }
});

Be carefull with the nested variable. 注意嵌套变量。 You have the same name for de readed array and for the function asigned variable. 读取数组和函数赋值变量的名称相同。

Good luck 祝好运

It should be like this : 应该是这样的:

var attendees={
attendees : [
    { name: 'John'},
    { name: 'Terry'}
]};



attendees.attendees.forEach(function(attendees){console.log(attendees.name);});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM