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


当前回答

如果你想使用 forEach(),它会看起来像 -

theArray.forEach ( element => {
    console.log(element);
});

如果你想使用(),它会看起来像 -

for(let idx = 0; idx < theArray.length; idx++){
    let element = theArray[idx];
    console.log(element);
}

其他回答

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

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

如果你不关心空白:

var x;

while(x = y.pop()){ 

    alert(x); //do something 

}

x 将包含 y 的最后值,并将从序列中删除。

Lambda Syntax 通常不适用于 Internet Explorer 10 或更低版本。

我通常使用

[].forEach.call(arrayName,function(value,index){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});

如果您是一个 jQuery 粉丝,并且已经有一个 jQuery 文件运行,您应该逆转指数和值参数的位置。

$("#ul>li").each(function(**index, value**){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});

这是一个非分散列表的 iterator,指数从0开始,这是处理document.getElementsByTagName或document.querySelectorAll时的典型场景)

function each( fn, data ) {

    if(typeof fn == 'string')
        eval('fn = function(data, i){' + fn + '}');

    for(var i=0, L=this.length; i < L; i++) 
        fn.call( this[i], data, i );   

    return this;
}

Array.prototype.each = each;  

使用例子:

例子 #1

var arr = [];
[1, 2, 3].each( function(a){ a.push( this * this}, arr);
arr = [1, 4, 9]

例子 #2

each.call(document.getElementsByTagName('p'), "this.className = data;",'blue');

每個 p 標籤都會得到 class="blue"

例子 #3

each.call(document.getElementsByTagName('p'), 
    "if( i % 2 == 0) this.className = data;",
    'red'
);

每個其他 p 標籤都會得到 class="red">

例子 #4

each.call(document.querySelectorAll('p.blue'), 
    function(newClass, i) {
        if( i < 20 )
            this.className = newClass;
    }, 'green'
);

最后,第一个20个蓝色P标签变成绿色

使用字符串作为函数时要小心:函数是由背景外创建的,并且应该仅在您对变量调节的确定情况下使用。