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


当前回答

我也想添加这个作为一个逆转旋转的组成和上面的答案,谁也喜欢这个合成。

var foo = [object,object,object];
for (var i = foo.length, item; item = foo[--i];) {
    console.log(item);
}

福利:

这一点的好处:你已经在第一个类似的参考,不需要以后与另一个线声明。

麻烦:

这将打破,每当参考是虚假 - 虚假(不定义,等)。它可以作为一个优点,但是,它会使它稍微更难阅读。

其他回答

一个 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
  }
);

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

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

使用到...可能的地方

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 */
}

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

我會說,為 / 是走的路:

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( )的文章。

最接近您的想法的方式将是使用 Array.forEach() 接受关闭函数,该函数将适用于序列的每个元素。

myArray.forEach(
  (item) => {
    // Do something
    console.log(item);
  }
);

另一种可行的方式是使用 Array.map() 以相同的方式工作,但它也需要所有值,你返回并返回它们在一个新的序列(基本上将每个元素地图到一个新的),如下:

var myArray = [1, 2, 3];
myArray = myArray.map(
  (item) => {
    return item + 1;
  }
);

console.log(myArray); // [2, 3, 4]