Iterate over a JavaScript array without using nested for-loops

前端 未结 2 2050
孤独总比滥情好
孤独总比滥情好 2020-12-14 13:57

I\'ve been trying to iterate over a multidimensional array in JavaScript, and print each element in the array. Is there any way to print each element in a multidimensional a

2条回答
  •  無奈伤痛
    2020-12-14 14:18

    If you don't want to use nested loops, you can either flat the array or use a recursive function. Something like:

    arr.forEach(function each(item) {
      if (Array.isArray(item))
        item.forEach(each);
      else
        console.log(item)
    });
    

提交回复
热议问题