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


当前回答

你可以使用:

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。

其他回答

这是一个非分散列表的 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标签变成绿色

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

如果您正在使用 jQuery 图书馆,您可以使用 jQuery.each:

$.each(yourArray, function(index, value) {
  // do your stuff here
});

编辑:

作为一个问题,用户想要代码在JavaScript而不是jquery,所以编辑是

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

在 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. 要停止执行,请使用 Array#some 如下:

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

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

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

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