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


当前回答

我也想添加这个作为一个逆转旋转的组成和上面的答案,谁也喜欢这个合成。

var foo = [object,object,object];
for (var i = foo.length, item; item = foo[--i];) {
    console.log(item);
}

福利:

这一点的好处:你已经在第一个类似的参考,不需要以后与另一个线声明。

麻烦:

这将打破,每当参考是虚假 - 虚假(不定义,等)。它可以作为一个优点,但是,它会使它稍微更难阅读。

其他回答

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

在 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

如果你想通过一系列用箭函数的对象旋转:

let arr = [{name:'john', age:50}, {name:'clark', age:19}, {name:'mohan', age:26}]; arr.forEach((person)=>{ console.log('I am ' + person.name + ' and I am ' + person.age + ' old'); })

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

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

我知道这是一个古老的帖子,而且已经有很多很好的答案。 为了更完整的我想象我会扔在另一个使用AngularJS. 当然,这只适用于如果你使用Angular,显然,然而,我会喜欢把它无论如何。

第一個論點是對象(命令)以 iterate 上,第二個論點是 iterator 函數,而選擇的第三個論點是對象背景(基本上提到在輪內的「這」)。

var temp = [1, 2, 3];
angular.forEach(temp, function(item) {
    //item will be each element in the array
    //do something
});

var temp = [1, 2, 3];
var temp2 = [];
angular.forEach(temp, function(item) {
    this.push(item); //"this" refers to the array passed into the optional third parameter so, in this case, temp2.
}, temp2);

angular.forEach(temp, function(item) {
    temp2.push(item);
});

福利

易于阅读 易于写作 如果可用, angular.forEach 将使用 ES5 forEach loop. 现在,我会得到效率,因为 forEach loop 比 loops 更慢。

angular.forEach(obj1.results, function(result1) {
    angular.forEach(obj2.results, function(result2) {
        if (result1.Value === result2.Value) {
            //do something
        }
    });
});

//exact same with a for loop
for (var i = 0; i < obj1.results.length; i++) {
    for (var j = 0; j < obj2.results.length; j++) {
        if (obj1.results[i].Value === obj2.results[j].Value) {
            //do something
        }
    }
}