我如何通过一个序列中的所有输入,使用JavaScript?


当前回答

如果您想保持代码的功能,请使用地图:

theArray.map(instance => do_something);

在这种情况下,您将为未来的操作创建一个新的序列,并将错过任何不需要的副作用。

其他回答

如果您想保持代码的功能,请使用地图:

theArray.map(instance => do_something);

在这种情况下,您将为未来的操作创建一个新的序列,并将错过任何不需要的副作用。

我會說,為 / 是走的路:

const arr = ['a', 'b', 'c']; for (const v of arr) { console.log(v); // 打印“a”,“b”,“c” }

例如,如果您设置 arr.foo = 'test', for (var v in arr) 将通过 'foo' 密钥旋转. 不同于 forEach(), for/of 不会错过'洞' 在 序列. const arr = ['a', 'c'] 是有效的 JavaScript, 只有 2 个元素是'洞'. 序列功能相当于 ['a', undefined, 'c'].

您可以在此博客中阅读更多关于 for/of vs forEach( )的文章。

Iterators 提高效率,让您同时消耗列表中的物品,就好像它们是流。 使 iterator 特别的是它通过收藏的方式. 其他插槽需要将整个收藏上传到前面,以便在收藏中进行 iterate,而 iterator 只需要知道收藏中的当前位置。

您可以通过呼叫 iterator 的下一个方法访问当前项目,下一个方法将返回当前项目的值,并将一个 boolean 指示您到达收藏结束时。

您也可以使用 Symbol.iterator 将您的常规序列转换为 iterator 如下:

您也可以将您的常规序列转换为这样的 iterator:

注意事项:

对象不默认可用,在这种情况下使用为..in,因为而不是值,它用钥匙工作。

我来自Python,我发现这种方式更清晰。

theArray 是 array,例子是 array 的元素:

for (let instance of theArray)
{
    console.log("The instance", instance);
}

for (instance in theArray)
{
    console.log("The instance", instance);
}

与比较:

theArray.forEach(function(instance) {
    console.log(instance);
});

但是,在一天结束时,两人都在做同样的事情。

Lambda Syntax 通常不适用于 Internet Explorer 10 或更低版本。

我通常使用

[].forEach.call(arrayName,function(value,index){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});

如果您是一个 jQuery 粉丝,并且已经有一个 jQuery 文件运行,您应该逆转指数和值参数的位置。

$("#ul>li").each(function(**index, value**){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});