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


当前回答

你可以这样打电话给每个人:

forEach 将在您提供的序列上进行 iterate 并为每个 iteration 将有保持该 iteration 的值的元素. 如果您需要索引,您可以通过 i 作为 forEach 的呼叫回复函数中的第二个参数获得当前指数。

Foreach 基本上是一种高顺序函数,它作为其参数需要另一个函数。

let theArray= [1,3,2];

theArray.forEach((element) => {
  // Use the element of the array
  console.log(element)
}

出口:

1
3
2

你也可以在这样的序列上进行 iterate:

for (let i=0; i<theArray.length; i++) {
  console.log(i); // i will have the value of each index
}

其他回答

某些 C 风格的语言使用 foreach 通过列表旋转。 在 JavaScript 中,这与 for..in 旋转结构进行:

var index,
    value;
for (index in obj) {
    value = obj[index];
}

要避免通过对象的原型继承的阅读值,只需检查是否属于对象的财产:

for (i in obj) {
    if (obj.hasOwnProperty(i)) {
        //do stuff
    }
}

此外,ECMAScript 5 已添加一个 forEach 方法到 Array.prototype 可以用来列出一个序列,使用一个字符串(多字符串在文件中,所以你仍然可以使用它在更老的浏览器):

arr.forEach(function (val, index, theArray) {
    //do stuff
});

重要的是要注意的是,当通话返回虚假时,Array.prototype.forEach 不会破裂。 jQuery 和 Underscore.js 提供各自的变量,以提供可以短循环的漏洞。

jQuery 使用 $.map 的方式:

var data = [1, 2, 3, 4, 5, 6, 7];

var newData = $.map(data, function(element) {
    if (element % 2 == 0) {
        return element;
    }
});

// newData = [2, 4, 6];

我會說,為 / 是走的路:

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

使用到...可能的地方

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

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

最接近您的想法的方式将是使用 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]