Подтвердить что ты не робот

В nodeJs есть ли способ для цикла через массив без использования размера массива?

Скажем, у меня

myArray = ['item1', 'item2']

Я пробовал

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

Он печатает   0   1

Я хочу, чтобы   item1   элемент2

Есть ли другой синтаксис, который работает без использования

for (var i = 0; i < myArray.length; i++)
4b9b3361

Ответ 1

Вы можете использовать Array.forEach

var myArray = ['1','2',3,4]

myArray.forEach(function(value){
  console.log(value);
});

Ответ 2

То, что вы, вероятно, хотите, for... of, относительно новой конструкции, созданной для явной цели перечисления значений итерируемых объектов:

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

Ответ 3

Чтобы напечатать "item1", "item2", этот код будет работать.

var myarray = ['hello', ' hello again'];

for (var item in myarray) {
    console.log(myarray[item])
}

Ответ 4

В ES5 нет эффективного способа итерации по разреженному массиву без использования свойства length. В ES6 вы можете использовать for...of. Возьмем следующие примеры:

'use strict';

var arr = ['one', 'two', undefined, 3, 4],
    output;

arr[6] = 'five';

output = '';
arr.forEach(function (val) {
    output += val + ' ';
});
console.log(output);

output = '';
for (var i = 0; i < arr.length; i++) {
    output += arr[i] + ' ';
}
console.log(output);

output = '';
for (var val of arr) {
    output += val + ' ';
};
console.log(output);
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="//gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Ответ 5

Использовать итераторы...

var myarray = ['hello', ' hello again'];
processArray(myarray[Symbol.iterator](), () => {
    console.log('all done')
})
function processArray(iter, cb) {
    var curr = iter.next()
    if(curr.done)
        return cb()
    console.log(curr.value)
    processArray(iter, cb)
}

Более подробный обзор: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

Ответ 6

    var count=0;
    let myArray = '{"1":"a","2":"b","3":"c","4":"d"}'
    var data = JSON.parse(myArray);
    for (let key in data) {
      let value =  data[key]; // get the value by key
      console.log("key: , value:", key, value);
      count = count + 1;
    }
   console.log("size:",count);

Ответ 7

Это естественный вариант JavaScript

var myArray = ['1','2',3,4]

myArray.forEach(function(value){
  console.log(value);
});

Ответ 8

Используйте встроенную функцию Javascript, называемую map..map() сделает то, что вы ищете!