我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
console.log("Index" + index);
console.log("Element" + item);
})
其他回答
某些 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 提供各自的变量,以提供可以短循环的漏洞。
一个 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
}
);
你可以使用:
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。
现在一个简单的解决方案是使用 underscore.js 图书馆,它提供了许多有用的工具,如每一个,并将自动将工作分配给原住民的Each 如果可用。
一个CodePen的例子,它是如何工作:
var arr = ["elemA", "elemB", "elemC"];
_.each(arr, function(elem, index, ar)
{
...
});
看也
在 for_each...in(MDN)中,它解释说,对于每个(对象变量)是作为ECMA-357(EAX)标准的一部分,而对于(MDN)来说,它描述了使用(对象变量)为(对象变量)作为和谐(ECMAScript 6)提议的一部分的下一个方法。
假设我们有几个主题:
let ddl = new Array();
if (subjects) {
subjects.forEach(function (s) {ddl.push({"id": s.id, "label": s.name});});
}