var obj = { \'a\' : \'apple\', \'b\' : \'banana\', \'c\' : \'carrot\' }
If I do a
for(key in obj) {
console.log( key + \' has a value
don't use for (key in obj)
, it will iterate over all enumerable properties including prototype properties, and can lead to amazingly horrible things. Modern JS has a special function for getting only the relevant keys out of an object, using Object.keys(...), so if you use var keys = Object.keys(obj)
to get the list of keys as an array, you can then iterate over that:
// blind iteration
Object.keys(obj).forEach(function(key, i) {
var value = obj[key];
// do what you need to here, with index i as position information.
// Note that you cannot break out of this iteration, although you
// can of course use ".some()" rather than ".forEach()" for that.
});
// indexed iteration
for(var keys = Object.keys(obj), i = 0, end = keys.length; i < end; i++) {
var key = keys[i], value = obj[key];
// do what you need to here, with index i as position information,
// using "break" if you need to cut the iteration short.
});
or select its last element immediately
var keys = Object.keys(obj);
var last = keys[keys.length-1];
or using a slice:
var keys = Object.keys(obj);
var last = keys.slice(-1)[0];
or using a shift (but that's a destructive operation, so we're not caching the keys because the shift turns it into "not all the keys anymore"):
var last = Object.keys(obj).shift();