javascript 如何识别 for..in 循环中的第一次迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18936732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to identify the first iteration in a for..in loop
提问by karavanjo
We have a loop like this:
我们有一个这样的循环:
for (var prop in obj) {
if (obj.hasOwnProperty(prop) {
// Here need operation only for first iteration (1)
// Other operations
}
}
How can we identify first iteration in (1)?
我们如何识别(1)中的第一次迭代?
回答by user2357112 supports Monica
If you can, move it out of the loop:
如果可以,请将其移出循环:
do_one_time_thing();
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// Other operations
}
}
Otherwise, set a flag, and lower it after the first iteration:
否则,设置一个标志,并在第一次迭代后降低它:
var first_iteration = true;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (first_iteration) {
do_one_time_thing();
first_iteration = false;
}
// Other operations
}
}
回答by wu-sama
you can use forEach
你可以使用 forEach
array.forEach((element,index) => {
if(index==0){
// first element
}else{
// not first element
}
});
回答by Paul Roub
Since there's no loop counter, you need to track this yourself:
由于没有循环计数器,您需要自己跟踪:
var first = true;
for (var prop in obj) {
if (obj.hasOwnProperty(prop) {
if (first) {
first = false;
// Here need operation only for first iteration (1)
}
// Other operations
}
}
回答by fardjad
Properties are not guaranteed to be listed in a predictable order (as others said).
不能保证以可预测的顺序列出属性(正如其他人所说)。
So you can use Object.keysto get the object properties as an array, sort that array and get the first element:
因此,您可以使用Object.keys将对象属性作为数组获取,对该数组进行排序并获取第一个元素:
var firstProperty = Object.keys(obj).sort()[0];
// firstValue = obj[firstProperty];
回答by user2736012
Assuming you don't care what the first item is, then you can use Object.keys()
with .forEach()
to avoid using a flag.
假设您不关心第一项是什么,那么您可以使用Object.keys()
with.forEach()
来避免使用标志。
With this, you also don't need to use .hasOwnProperty()
, because Object.keys()
handles that for you.
有了这个,您也不需要使用.hasOwnProperty()
,因为Object.keys()
它会为您处理。
Object.keys(obj).forEach(function(key, i) {
if (i === 0) {
console.log("first", obj[key]);
}
console.log(obj[key]);
});