How to get the last item in a javascript-value object with a for loop?

后端 未结 6 2207
长情又很酷
长情又很酷 2021-02-07 06:11
var obj = { \'a\' : \'apple\', \'b\' : \'banana\', \'c\' : \'carrot\' }

If I do a

for(key in obj) {
  console.log( key + \' has a value         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-07 06:21

    You could loop through all of them and save the last one in a variable.

    var lastItem = null;
    for(key in obj) {
      console.log( key + ' has a value ' + obj[key] );
      lastItem = key;
    }
    // now the last iteration's key is in lastItem
    console.log('the last key ' + lastItem + ' has a value ' + obj[lastItem]);
    

    Also, because of how JavaScript works the key is also in your loop's key variable, so the extra variable is not even needed.

    for(key in obj) {
      console.log( key + ' has a value ' + obj[key] );
    }
    // now the last iteration's key is in key
    console.log('the last key ' + key + ' has a value ' + obj[key]);
    

提交回复
热议问题