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.
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
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.
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.
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.
.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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With