我有一个obj:
let obj = {
1: 'one',
2: 'two',
3: 'three',
7: 'seven'
}
是否有机会从 3 个位置开始迭代它,如下所示:
for (let key = 3 in obj) {
console.log(obj[key]) // An output will be 'three' and 'seven'
}
我需要以最快的方式做到这一点,因为 obj 非常大
只需通过简单的方式进行操作即可。
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]);
}
如果键小于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);
}
您可以通过多种方式实现此目的。一种算法涉及将对象转换为数组。然后确定中点。
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)
}
})