[英]How can I iterate (for key in obj) starting middle position
I have an obj: 我有一个obj:
let obj = {
1: 'one',
2: 'two',
3: 'three',
7: 'seven'
}
Is there an opportunity to iterate it starting 3 position, like this: 是否有机会迭代它的第3个位置,如下所示:
for (let key = 3 in obj) {
console.log(obj[key]) // An output will be 'three' and 'seven'
}
I need to do this by the fastest way, because an obj is very huge 我需要以最快的方式执行此操作,因为obj非常大
You can use the continue
to skip the iteration if the key is less than 3
: 如果键小于
3
则可以使用continue
跳过迭代:
let obj = { 1: 'one', 2: 'two', 3: 'three', 7: 'seven' }; for(let [key, val] of Object.entries(obj)){ if(key < 3 ){ continue; } console.log(val); }
You can accomplish this in many ways. 您可以通过多种方式完成此任务。 One algorithm would involve turning the object into an array.
一种算法将涉及将对象变成数组。 And then identifying the mid-point.
然后确定中点。
let obj = {
1: 'one',
2: 'two',
3: 'three',
7: 'seven'
}
Object.entries(obj).forEach(([key, value], index, array) => {
const split = array.length/2
const midPoint = split % 2 == 0 ? split : Math.floor(split)
if(index >= midPoint){
console.log(key)
}
})
Just do it by a simple way. 只需通过一种简单的方法即可。
let obj = {
1: 'one',
2: 'two',
3: 'three',
7: 'seven'
};
// make sure that your case is in order
// get keys of your object
const keys = Object.keys(obj);
// find index of starting key
const index = keys.indexOf('3');
// make sure index >= 0
// each all keys from starting key to the end by old school way
for (let i = index; i < keys.length; i++) {
var key = keys[i];
console.log(obj[key]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.