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


当前回答

如果您想保持代码的功能,请使用地图:

theArray.map(instance => do_something);

在这种情况下,您将为未来的操作创建一个新的序列,并将错过任何不需要的副作用。

其他回答

某些 C 风格的语言使用 foreach 通过列表旋转。 在 JavaScript 中,这与 for..in 旋转结构进行:

var index,
    value;
for (index in obj) {
    value = obj[index];
}

要避免通过对象的原型继承的阅读值,只需检查是否属于对象的财产:

for (i in obj) {
    if (obj.hasOwnProperty(i)) {
        //do stuff
    }
}

此外,ECMAScript 5 已添加一个 forEach 方法到 Array.prototype 可以用来列出一个序列,使用一个字符串(多字符串在文件中,所以你仍然可以使用它在更老的浏览器):

arr.forEach(function (val, index, theArray) {
    //do stuff
});

重要的是要注意的是,当通话返回虚假时,Array.prototype.forEach 不会破裂。 jQuery 和 Underscore.js 提供各自的变量,以提供可以短循环的漏洞。

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

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

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

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'); })

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

如果你不关心空白:

var x;

while(x = y.pop()){ 

    alert(x); //do something 

}

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