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


当前回答

在 jQuery 中,有三种实施。

var a = [3,2];

$(a).each(function(){console.log(this.valueOf())}); //Method 1
$.each(a, function(){console.log(this.valueOf())}); //Method 2
$.each($(a), function(){console.log(this.valueOf())}); //Method 3

其他回答

注意: 这个答案是毫无希望的日期。 为了更现代化的方法,请参见在序列上可用的方法。

forEach 地图过滤器 ZIP 减少每一个


在JavaScript中引用一个序列的标准方式是Vanilla for-loop:

var length = arr.length,
    element = null;
for (var i = 0; i < length; i++) {
  element = arr[i];
  // Do something with element
}

但是,请注意,这种方法只有在你有一个密集的序列,每个指数都被一个元素占据。 如果序列是分散的,那么你可以运行到性能问题与这个方法,因为你会 iterate上很多指标,实际上不存在在序列。 在这种情况下,一个为.. in-loop 可能是一个更好的想法。

在 ECMAScript 5 将有一个 forEach 方法在序列的原型,但它不支持在遗产浏览器. 因此,能够连续使用它,你必须有一个环境支持它(例如,Node.js 服务器侧 JavaScript),或使用一个“Polyfill”。 该功能的 Polyfill 是,然而,三角形,因为它使代码更容易阅读,它是一个好 polyfill。

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

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

可能為(i = 0; i < array.length; i++) loop 不是最好的選擇. 為什麼? 如果你有這個:

var array = new Array();
array[1] = "Hello";
array[7] = "World";
array[11] = "!";

方法将从序列(0)到序列(2). 首先,这将是你甚至没有的参考变量,第二,你不会有序列中的变量,第三,这将使代码泡沫。

for(var i in array){
    var el = array[i];
    //If you want 'i' to be INT just put parseInt(i)
    //Do something with el
}

如果你想要它成为一个功能,你可以这样做:

function foreach(array, call){
    for(var i in array){
        call(array[i]);
    }
}

如果你想打破,更有逻辑:

function foreach(array, call){
    for(var i in array){
        if(call(array[i]) == false){
            break;
        }
    }
}

例子:

foreach(array, function(el){
    if(el != "!"){
        console.log(el);
    } else {
        console.log(el+"!!");
    }
});

它回来了:

//Hello
//World
//!!!

您可以使用图书馆获得此功能(我建议 Underscore.js),使用一个简单的在路径。

for (var instance in objects) {
   ...
}

但是,请注意,可能有理由使用一个更简单的旋转(见 Stack Overflow 问题 为什么使用“为”与序列调节这样的坏想法?)

var instance;
for (var i=0; i < objects.length; i++) {
    var instance = objects[i];
    ...
}

根据新更新 ECMAScript 6 (ES6) 和 ECMAScript 2015 的功能,您可以使用以下选项:

对于洛普

for(var i = 0; i < 5; i++){
  console.log(i);
}

// Output: 0,1,2,3,4

上一篇:在洛普斯

let obj = {"a":1, "b":2}

for(let k in obj){
  console.log(k)
}

// Output: a,b

Array.forEach( )

let array = [1,2,3,4]

array.forEach((x) => {
  console.log(x);
})

// Output: 1,2,3,4

為...LOPS

let array = [1,2,3,4]

for(let x of array){
  console.log(x);
}

// Output: 1,2,3,4

當LOPS

let x = 0

while(x < 5){
  console.log(x)
  x++
}

// Output: 1,2,3,4

此分類上一篇: while loops

let x = 0

do{
  console.log(x)
  x++
}while(x < 5)

// Output: 1,2,3,4