我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
如果你想在一个序列上旋转,请使用标准的三部分旋转。
for (var i = 0; i < myArray.length; i++) {
var arrayItem = myArray[i];
}
您可以通过缓存 myArray.length 或向后转向它获得某些性能优化。
其他回答
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);
});
现在一个简单的解决方案是使用 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)提议的一部分的下一个方法。
根据新更新 ECMAScript 6 (ES6) 和 ECMAScript 2015 的功能,您可以使用以下选项:
对于洛普
for(var i = 0; i < 5; i++){
console.log(i);
}
// Output: 0,1,2,3,4
上一篇:在洛普斯
let obj = {"a":1, "b":2}
for(let k in obj){
console.log(k)
}
// Output: a,b
Array.forEach( )
let array = [1,2,3,4]
array.forEach((x) => {
console.log(x);
})
// Output: 1,2,3,4
為...LOPS
let array = [1,2,3,4]
for(let x of array){
console.log(x);
}
// Output: 1,2,3,4
當LOPS
let x = 0
while(x < 5){
console.log(x)
x++
}
// Output: 1,2,3,4
此分類上一篇: while loops
let x = 0
do{
console.log(x)
x++
}while(x < 5)
// Output: 1,2,3,4
假设我们有几个主题:
let ddl = new Array();
if (subjects) {
subjects.forEach(function (s) {ddl.push({"id": s.id, "label": s.name});});
}
您可以使用图书馆获得此功能(我建议 Underscore.js),使用一个简单的在路径。
for (var instance in objects) {
...
}
但是,请注意,可能有理由使用一个更简单的旋转(见 Stack Overflow 问题 为什么使用“为”与序列调节这样的坏想法?)
var instance;
for (var i=0; i < objects.length; i++) {
var instance = objects[i];
...
}