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


当前回答

现在一个简单的解决方案是使用 underscore.js 图书馆,它提供了许多有用的工具,如每一个,并将自动将工作分配给原住民的Each 如果可用。

一个CodePen的例子,它是如何工作:

var arr = ["elemA", "elemB", "elemC"];
_.each(arr, function(elem, index, ar)
{
...
});

看也

在 for_each...in(MDN)中,它解释说,对于每个(对象变量)是作为ECMA-357(EAX)标准的一部分,而对于(MDN)来说,它描述了使用(对象变量)为(对象变量)作为和谐(ECMAScript 6)提议的一部分的下一个方法。

其他回答

我来自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);
});

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

一个 forEach 实施(见 jsFiddle):

function forEach(list,callback) {
  var length = list.length;
  for (var n = 0; n < length; n++) {
    callback.call(list[n]);
  }
}

var myArray = ['hello','world'];

forEach(
  myArray,
  function(){
    alert(this); // do something
  }
);

使用到...可能的地方

async/await support Skips non-numeric props Immutable index
for...of
forEach()
for...in
Regular for

正如上面的表中可以看到的那样,它应该随时随地使用,因为它支持非同步功能,并通过随机修改曲线指数来阻止非数字特性。

合成

const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const num of nums) {
  /* Do something with num */
}

查看更多例子的参考,链接到规格和与与与与与之间的差异,或者可能检查这个教程,以了解它们如何不同。

总结:

创建新序列:地图

let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(元素,索引,序列) => {返回元素 * 2; }) console.log(arr); console.log(newArr);

forEach 是一种位于 Array.prototype 的函数,它将作为一个论点采取呼叫回归函数,然后对序列中的每个元素进行此呼叫回归函数,与地图() 函数不同,forEach 函数不会返回任何东西(未定义)。

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

theArray.map(instance => do_something);

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