簡體   English   中英

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM