我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
您可以使用图书馆获得此功能(我建议 Underscore.js),使用一个简单的在路径。
for (var instance in objects) {
...
}
但是,请注意,可能有理由使用一个更简单的旋转(见 Stack Overflow 问题 为什么使用“为”与序列调节这样的坏想法?)
var instance;
for (var i=0; i < objects.length; i++) {
var instance = objects[i];
...
}
其他回答
我来自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 ddl = new Array();
if (subjects) {
subjects.forEach(function (s) {ddl.push({"id": s.id, "label": s.name});});
}
使用到...可能的地方
async /await support |
Skips non-numeric props | Immutable index | |
---|---|---|---|
for...of |
✅ | ✅ | ✅ |
forEach() |
❌ | ✅ | ✅ |
for...in |
✅ | ❌ | ✅ |
Regular for |
✅ | ✅ | ❌ |
正如上面的表中可以看到的那样,它应该随时随地使用,因为它支持非同步功能,并通过随机修改曲线指数来阻止非数字特性。
合成
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const num of nums) {
/* Do something with num */
}
查看更多例子的参考,链接到规格和与与与与与之间的差异,或者可能检查这个教程,以了解它们如何不同。
我會說,為 / 是走的路:
const arr = ['a', 'b', 'c']; for (const v of arr) { console.log(v); // 打印“a”,“b”,“c” }
例如,如果您设置 arr.foo = 'test', for (var v in arr) 将通过 'foo' 密钥旋转. 不同于 forEach(), for/of 不会错过'洞' 在 序列. const arr = ['a', 'c'] 是有效的 JavaScript, 只有 2 个元素是'洞'. 序列功能相当于 ['a', undefined, 'c'].
您可以在此博客中阅读更多关于 for/of vs forEach( )的文章。
如果您正在使用 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].
}