最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Last iteration in foreach loop with Object Javascript - Stack Overflow

programmeradmin5浏览0评论

I have an object like this.

objName {
 item1 : someItem,
 item2 : someItem,
 item3 : someItem,
}

Now the number of property is dynamic and can be increase in unknown amount, I am performing a foreach loop in the property key on this object like this.

Object.keys(objName).forEach(itemNumber => {
console.log(itemNumber);
});

How am I going to detect the very last iteration of it to perform a new task?

I have an object like this.

objName {
 item1 : someItem,
 item2 : someItem,
 item3 : someItem,
}

Now the number of property is dynamic and can be increase in unknown amount, I am performing a foreach loop in the property key on this object like this.

Object.keys(objName).forEach(itemNumber => {
console.log(itemNumber);
});

How am I going to detect the very last iteration of it to perform a new task?

Share Improve this question edited Nov 21, 2018 at 13:58 Mihae Kheel asked Nov 21, 2018 at 13:37 Mihae KheelMihae Kheel 2,6513 gold badges19 silver badges41 bronze badges 4
  • The question is not clear – brk Commented Nov 21, 2018 at 13:38
  • i need to detect the very last iteration like declaring a var number that will increment while the length of object's property is equal to var number but since I am new javascript object I do not know where to start. – Mihae Kheel Commented Nov 21, 2018 at 13:41
  • the object length key here is 3 right? – Mihae Kheel Commented Nov 21, 2018 at 13:41
  • Code updated sorry... – Mihae Kheel Commented Nov 21, 2018 at 13:44
Add a ment  | 

3 Answers 3

Reset to default 12

You could use index and array parameters to check if there is next element. You can also check if current index is equal length - 1 index == arr.length - 1

let objName = {
 item1 : "someItem",
 item2 : "someItem",
 item3 : "someItem",
}

Object.keys(objName).forEach((item, index, arr) => {
  console.log(item);
  if(!arr[index + 1]) console.log('End')
});

You can pass index and value to forEach function like the code below and use Object.keys(objName).length to get the object length then the last member objName[value]

 var objName = {
 item1 : "someItem",
 item2 : "someItem",
 item3 : "someItem3",
}
Object.keys(objName).forEach((value, index) => {
if(index==Object.keys(objName).length-1){
  console.log(objName[value]);
}
});

First find the length of the object like below:

var objLength= Object.keys(objName).length;

Then you can use like this:

var count = 0;

Object.keys(objName).forEach(item => {
    console.log(item);
    count++;
    if (count == objLength)
    {
        console.log("endOfLoop");
    }
});
发布评论

评论列表(0)

  1. 暂无评论