For loop in multidimensional javascript array

前端 未结 8 1518
我在风中等你
我在风中等你 2020-11-28 21:28

Since now, I\'m using this loop to iterate over the elements of an array, which works fine even if I put objects with various properties inside of it.

var cu         


        
8条回答
  •  被撕碎了的回忆
    2020-11-28 22:13

    A bit too late, but this solution is nice and neat

    const arr = [[1,2,3],[4,5,6],[7,8,9,10]]
    for (let i of arr) {
      for (let j of i) {
        console.log(j) //Should log numbers from 1 to 10
      }
    }
    

    Or in your case:

    const arr = [[1,2,3],[4,5,6],[7,8,9]]
    for (let [d1, d2, d3] of arr) {
      console.log(`${d1}, ${d2}, ${d3}`) //Should return numbers from 1 to 9
    }
    

    Note: for ... of loop is standardised in ES6, so only use this if you have an ES5 Javascript Complier (such as Babel)

    Another note: There are alternatives, but they have some subtle differences and behaviours, such as forEach(), for...in, for...of and traditional for(). It depends on your case to decide which one to use. (ES6 also has .map(), .filter(), .find(), .reduce())

提交回复
热议问题