识别 Javascript 对象中的最后一次迭代
我有一个正在迭代的对象,
for (el in object) {
// Some work here
}
我想知道迭代内的最后一次迭代是什么时候,所以我可以做
for (el in object) {
// Some work here
if (last_iteration) {
// Do something
}
}
任何简单的方法来做到这一点?
I have an object that I'm iterating
for (el in object) {
// Some work here
}
I want to know when is the last iteration, inside the iteration, so I can do
for (el in object) {
// Some work here
if (last_iteration) {
// Do something
}
}
Any straightforward way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我知道我迟到了,但我刚刚遇到了这个问题并像这样修复了它:
更新:几年后,循环结束时的
i++
确实让我很恼火。或者
I know I'm late but I just ran into this and fixed it like this:
Update: A few years later,
i++
at the end of a loop really irks me.or
您可以执行以下操作:
以防万一您想以一种方式处理除最后一个元素之外的所有元素 (
doSomething
),并以另一种方式处理最后一个元素 (doSomethingElse
) )。如果您想以一种方式处理所有元素 (
doSomething
),并且只想对最后一个元素进行额外处理 (doSomethingExtra
),您可以执行以下操作 :更短的是,您可以通过重用
el
变量,即:希望这有帮助。
You can do something like this:
This is in case you want to process all but the last element in one way (
doSomething
) and process the last element in another way (doSomethingElse
).If you want to process all the elements in one way (
doSomething
) and want to have extra processing for the last element only (doSomethingExtra
), you can do:To make it even shorter, you can do similar to what Török Gábor did in the gist he provided, by reusing
el
variable, i.e.:Hope this helps.
如果键不是数字,则以下方法有效:
Object.keys() 方法返回一个数组给定对象自己的可枚举属性名称,以与正常循环相同的顺序进行迭代。
带有导致重新排序的数字键的示例:
If the keys are not numerical, this works:
The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
Example with numerical keys causing reordering:
请注意,只有当您要迭代的对象是数组(具有数字键)时,这才有效
请注意,
i
之前的+
符号是必需的,因为如果省略,它将执行字符串连接,键结果为01
,12、
23
等Note that this will only work if the object you are iterating over is an array (has numeric keys)
Note that the
+
sign beforei
is necessary since if omitted, it will do a string concatenation, the keys resulting in01
,12
,23
, etc如前所述,属性没有明显的顺序,因此最后枚举的属性只有在事后才知道。
as said already, there is no distinct order for properties, so last enumerated property is only known afterwards.