Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last loop in for()?

Tags:

javascript

I have been struggling with this for a while:

for( var key in obj ){
    blah.blah()
    if(choice){
         doThis();
    }
}

How can I call doThis() only at the last item? Since I don't have a counter, i, I can't determine which is the last item.

like image 863
Derek 朕會功夫 Avatar asked Jul 02 '26 18:07

Derek 朕會功夫


1 Answers

First off, keys don't come in any guaranteed order. By specification, the keys are unordered. If you really wanted to do something with the last key you got, you could do so like this;

var lastkey;
for( var key in obj ){
    lastkey = key;
    blah.blah()
}
if(choice){
    // use lastkey if you want
    doThis();
}
like image 175
jfriend00 Avatar answered Jul 04 '26 06:07

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!