jQuery - delete last object by key
Hi i have this object :
object {
key1:[.....],
key2:[....],
key3:[.... ]
}
how does i can delete the last object key (key3)?
i would like to be fre开发者_Go百科e to delete last object key without knowing anything about that key.
Thsi is the ES5-compatible way of doing it:
obj = {a : 1, b : 2, c : 3};
var k = Object.keys(obj);
delete obj[k[k.length-1]];
or shorter:
delete obj[Object.keys(obj)[Object.keys(obj).length-1]];
You can't assume that the last element added will be the last element listed in a javascript object. See this question: Elements order in a "for (… in …)" loop
In short: Use an array if order is important to you.
There is not "last" object key within an object in Javascript. Object keys are not ordered and hence, there cannot be first or last.
I guess, technically, the keys aren't in any specific order, but anyway...
var key;
for (key in obj);
delete obj[key];
It iterates over the whole object, and then deletes whatever was the last thing to be visited.
edit to illustrate
obj = {a : 1, b : 2, c : 3};
for (key in obj); // loops over the entire object, doing nothing *EXCEPT*
// updating the `key` variable
alert(key); // "c" ... the last value of `key` was 'c'
delete obj[key]; // remove obj.c
精彩评论