简体   繁体   English

如何在javascript中获取for(... in ...)循环的位置?

[英]How can I get the positions of a for ( … in … ) loop in javascript?

When looping over a javascript object using a for in loop, how can I access the position of the iterator inside the for loop? 当使用for in循环遍历javascript对象时,如何在for循环中访问迭代器的位置?

a = {some: 1, thing: 2};

for (obj in a) {
    if (/* How can I access the first iteration*/) {
       // Do something different on the first iteration
    }
    else {
       // Do something
    }
}

A Javascript object's properties have no ordering. Javascript对象的属性没有排序。 {some: 1, thing: 2} is the same as {thing: 2, some: 1} {some: 1, thing: 2}{thing: 2, some: 1}

But if you want to keep track using an iterator anyway, do this: 但是如果你想使用迭代器继续跟踪,请执行以下操作:

var i = 0;
for (obj in a) {
    if (i == 0) {
       // Do something different on the first iteration
    }
    else {
       // Do something
    }
    i ++;
}

As far as I am aware there's no innate way to do so, and there's no way to know which is the first item, the order of the properties are arbitrary. 据我所知,没有天生的方法这样做,并且无法知道哪个是第一个项目,属性的顺序是任意的。 If there's something you only want to do once, well, that's incredibly simple, you just keep a manual iterator, but I'm not sure if that's what you're asking for. 如果有什么你只想做一次,那么,这非常简单,你只需要一个手动迭代器,但我不确定这是不是你要求的。

a = {some: 1, thing: 2};
var first = true;

for (obj in a) {
    if (first) {
       first = false;
       // Do something different on the first iteration
    }
    else {
       // Do something
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM