Javascript 在 nodeJs 中,有没有办法在不使用数组大小​​的情况下遍历数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29397746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:18:04  来源:igfitidea点击:

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

javascriptnode.js

提问by user310291

Let's say I have

假设我有

myArray = ['item1', 'item2']

I tried

我试过

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

It prints 0 1

它打印 0 1

What I wish is to have item1 item2

我希望有 item1 item2

Is there any other syntax that works without using

是否有任何其他语法可以在不使用的情况下工作

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

回答by makenova

You can use Array.forEach

您可以使用 Array.forEach

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

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

回答by canon

What you probably want is for...of, a relatively new construct built for the express purpose of enumerating the values of iterable objects:

您可能想要的是,一个相对较新的构造,用于枚举可迭代对象的值的明确目的:for...of

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

... as distinct from for...in, which enumerates property names(presumably1numeric indices in the case of arrays). Your loop displayed unexpected results because you didn't use the property names to get the corresponding values via bracket notation... but you could have:

... 不同于,它枚举属性名称(在数组的情况下大概是1 个数字索引)。您的循环显示了意外结果,因为您没有使用属性名称通过括号表示法获取相应的值……但您可以:for...in

let myArray = ["a","b","c","d"];
for (let key in myArray) {
  let value =  myArray[key]; // get the value by key
  console.log("key: %o, value: %o", key, value);
}

1Unfortunately, someone may have added enumerable propertiesto the array or its prototype chain which are notnumeric indices... or they may have assigned an index leaving unassigned indices in the interim range. The issues are explained pretty well here. The main takeaway is that it's best to loop explicitly from 0to array.length - 1rather than using for...in.

1不幸的是,有人可能向数组或其原型链中添加了不是数字索引的可枚举属性……或者他们可能分配了一个索引,在中间范围内留下了未分配的索引。这些问题在这里得到了很好的解释。主要结论是最好从to显式循环而不是使用.0array.length - 1for...in

So, this is not (as I'd originally thought) an academic question, i.e.:

所以,这不是(正如我最初认为的)一个学术问题,即:

Without regard for practicality, is it possibleto avoid lengthwhen iterating over an array?

如果没有对方面的实用性,是它能够避免length迭代时,一个数组?

According to your comment(emphasis mine):

根据您的评论(强调我的):

[...] why do I need to calculate the sizeof an array whereas the interpreter can know it.

[...] 为什么我需要计算数组的大小而解释器可以知道它。

You have a misguided aversion to Array.length. It's not calculated on the fly; it's updated whenever the length of the array changes. You're not going to see performance gains by avoiding it (apart from caching the array length rather than accessing the property):

你对. 它不是即时计算的;只要数组的长度发生变化,它就会更新。通过避免它,您不会看到性能提升(除了缓存数组长度而不是访问属性):Array.length

loop test

循环测试

Now, even if you did get some marginal performance increase, I doubt it would be enough to justify the risk of dealing with the aforementioned issues.

现在,即使您确实获得了一些边际性能提升,我怀疑这是否足以证明处理上述问题的风险是合理的。

回答by Shikhar Saxena

To print 'item1' , 'item2', this code would work.

要打印 'item1' 、 'item2',此代码将起作用。

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

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

回答by Itamar Lev

This is the natural javascript option

这是自然的 javascript 选项

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

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

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

但是,如果您在forEach 循环中使用await它将不起作用,因为 forEach 不是异步的。您将被迫使用第二个答案或其他等效答案:

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

Or you could create an asyncForEach explained here:

或者你可以创建一个 asyncForEach 在这里解释:

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

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

回答by borisdiakur

In ES5 there is no efficient way to iterate over a sparsearray without using the length property. In ES6 you can use for...of. Take this examples:

在 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>

All array methods which you can use to iterate safely over densearrays use the lengthproperty of an object created by calling ToObjectinternaly. See for instance the algorithm used in the forEachmethod: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18However in es6, you can use for...ofsafely for iterating over sparse arrays.

所有可用于在密集数组上安全迭代的数组方法都使用length通过调用ToObjectinternaly创建的对象的属性。例如,参见该forEach方法中使用的算法:http: //www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18但是在 es6 中,您可以for...of安全地使用迭代稀疏数组。

See also Are Javascript arrays sparse?.

另请参阅Javascript 数组稀疏吗?.

回答by Mukesh Kumar

    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);

回答by decoder7283

Use Iterators...

使用迭代器...

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)
}

More in depth overview: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

更深入的概述:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

回答by user1789573

Use the built-in Javascript function called map. .map() will do the exact thing you're looking for!

使用名为 map 的内置 Javascript 函数。.map() 会做你正在寻找的确切的事情!