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

How can I get the positions of a for ( ... in ... ) loop in javascript?

本文关键字:in 循环 位置 for javascript 获取      更新时间:2023-09-26

使用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
    }
}

Javascript对象的属性没有排序。{some: 1, thing: 2}{thing: 2, some: 1} 相同

但是,如果您无论如何都想使用迭代器来跟踪,请执行以下操作:

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

据我所知,没有天生的方法可以做到这一点,也没有办法知道哪个是第一项,属性的顺序是任意的。如果有一件事你只想做一次,那么,这非常简单,你只需要保留一个手动迭代器,但我不确定这是否是你想要的。

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
    }
}