In nodeJs is there a way to loop through an array without using array size?

后端 未结 8 931
后悔当初
后悔当初 2021-02-01 11:56

Let\'s say I have

myArray = [\'item1\', \'item2\']

I tried

for (var item in myArray) {console.log(item)}

It

8条回答
  •  广开言路
    2021-02-01 12:49

    This is the natural javascript option

    var myArray = ['1','2',3,4]
    
    myArray.forEach(function(value){
      console.log(value);
    });

    However it won't work if you're using await inside the forEach loop because forEach is not asynchronous. you'll be forced to use the second answer or some other equivalent:

    let myArray = ["a","b","c","d"];
    for (let item of myArray) {
      console.log(item);
    }

    Or you could create an asyncForEach explained here:

    https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404

提交回复
热议问题