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