如何迭代(对于 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 非常大


慕田峪4524236
浏览 232回答 3
3回答

largeQ

只需通过简单的方法即可。let obj = {&nbsp; 1: 'one',&nbsp; 2: 'two',&nbsp; 3: 'three',&nbsp; 7: 'seven'};// make sure that your case is in order// get keys of your objectconst keys = Object.keys(obj);// find index of starting keyconst index = keys.indexOf('3');// make sure index >= 0// each all keys from starting key to the end by old school wayfor (let i = index; i < keys.length; i++) {&nbsp; var key = keys[i];&nbsp; console.log(obj[key]);}

慕婉清6462132

continue如果键小于 ,您可以使用跳过迭代3:let obj = {&nbsp; &nbsp; 1: 'one',&nbsp; &nbsp; 2: 'two',&nbsp; &nbsp; 3: 'three',&nbsp; &nbsp; 7: 'seven'};for(let [key, val] of Object.entries(obj)){&nbsp; &nbsp; &nbsp;if(key < 3 ){&nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; console.log(val);&nbsp;}

侃侃无极

您可以通过多种方式实现这一点。一种算法涉及将对象转换为数组。然后确定中点。let obj = {&nbsp; &nbsp; 1: 'one',&nbsp; &nbsp; 2: 'two',&nbsp; &nbsp; 3: 'three',&nbsp; &nbsp; 7: 'seven'}Object.entries(obj).forEach(([key, value], index, array) => {&nbsp; &nbsp; const split = array.length/2&nbsp; &nbsp; const midPoint = split % 2 == 0 ? split : Math.floor(split)&nbsp; &nbsp; if(index >= midPoint){&nbsp; &nbsp; &nbsp; &nbsp; console.log(key)&nbsp; &nbsp; }})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript