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


当前回答

关于ECMAScript6:

列表 = [0, 1, 2, 3] for (let obj of list) { console.log(obj) }

在哪里避免与内相关的异常,使它像任何其他语言的旋转一样工作,并让它在旋转中相反地连接到函数内。

手臂({})可以被忽略,如果只有一个命令(例如,在上面的例子)。

其他回答

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

我来自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 将在您提供的序列上进行 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
}

你可以使用:

ForEach theArray.forEach(功能(序列,索引) { console.log(索引); console.log(序列); }; for(var i=0; i<theArray.length; i++) { console.log(i) } 地图 theArray.map(x => console.log(x));地图 theArray.filter(x => console.log(x));

而且还有很多其他人为 iteration。

没有内置的能力打破 forEach. 要停止执行,请使用 Array#some 如下:

[1,2,3].some(function(number) {
    return number === 1;
});

這是因為有些回來是真實的,一旦任何的呼叫回來,執行在順序,回來是真實的,短循環的執行的其他。