This is similar to this question,only PHP->javascript
http://stackoverflow.com/questions/2197933/how-to-get-numeric-key-of-new-pushed-item-in-php
This is similar to this question,only PHP->javascript
http://stackoverflow.com/questions/2197933/how-to-get-numeric-key-of-new-pushed-item-in-php
var foo = myarray[myarray.length - 1];
The preferred term is element, rather than key.
EDIT: Or do you mean the last index? That is myarray.length - 1
. Keep in mind, JavaScript arrays can only be indexed numerically (though arrays are also objects, which causes some confusion).
The last key of an array is always arr.length-1
as arrays always start with key 0
:
var arr = new Array(3); // arr === [], arr.length === 3
arr.push(0); // arr === [undefined, undefined, undefined, 0], arr.length === 4
arr[arr.length-1] // returns 0
var arr = []; // arr === [], arr.length === 0
arr[3] = 0; // arr === [undefined, undefined, undefined, 0], arr.length === 4
arr[arr.length-1] // returns 0
If it's a flat array, this would do:
return array.length - 1;
However, if you have an associative array, you'd have to know the key and loop through it. Please note though that JavaScript knows no such thing as an "associative array", as most elements in JavaScript are objects.
Disclaimer: Usage of associative arrays in JavaScript is generally not a good practice and can lead to problems.
var x = new Array();
x['key'] = "value";
for (i in x)
{
if (i == 'key')
{
alert ("we got "+i);
}
}