Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use pop() with JavaScript Associative Arrays

How can I do something like the following in JS? I would like to imitate .pop() on an object rather than an array.

var deck = { 
    'cardK' :'13',
    'cardQ' :'12',
    'cardAJ':'11'
};

var val = deck.pop();


console.log("Key" + val.key ); 
console.log("Value" + val.val ); 

It seems like it's not possible.

like image 990
Il Profeta Profeta Avatar asked Feb 20 '14 06:02

Il Profeta Profeta


People also ask

What does Pop () method do when used with arrays?

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

Is Pop () destructive?

push() , pop() , shift() and unshift() are only four of many other such methods. These four array methods are quite similar to each other in the way they work and the fact that they are all destructive.

Does pop take arguments JavaScript?

pop(); Return values: Returns the element which is removed from the array. In case the array is empty then it returns “undefined”. Arguments: This method does not require any arguments/parameters.

Does JavaScript support associative array?

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.


1 Answers

.pop is only available on an array. In JavaScript, objects (which are essentially associative arrays) are not ordered like an array, so there is no .pop method.

You could use an array:

var deck = [
    { key: 'cardK', val: 13 },
    { key: 'cardQ', val: 12 },
    { key: 'cardAJ', val: 11 },
];

var val = deck.pop();
console.log('key: ' + val.key);
console.log('aa: ' + val.val);
like image 184
Ethan Brown Avatar answered Sep 24 '22 10:09

Ethan Brown