简体   繁体   中英

How to get last key in array in javascript?

This is similar to this question,only PHP->javascript

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).

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);
    }
}

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

first sorry for poor English. assume your array is "key associated array" with string keys in number format . you will need 3 step : get all array keys . convert array keys to integer. get max or length or any other keys property.

stringKeys= Object.keys(keyValueArray);//get keys of array 
integerKeys=stringKeys.map(Number);//convert to integer
mx=Math.max.apply(integerKeys);//get max
len=stringKeys.length;//get length 

hope i helped

Math.max(...[...myArray.keys()]);

Here myArray is the name of an array.

This is a solution based on your referred question. Assuming the array is a single dimensional array or all the array keys are numeric.

Reads: Math.max , Array.prototype.keys() , Iterators and generators

If your array is an associative array( Object ), I think the best way to do this is by using Object.keys() .

From MDN ;

The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.

First get the keys of the array in an numeric array.
Then get the last key, and use it in the Object.

var keys = Object.keys(my_array);
var last = keys[keys.length - 1];
console.log(my_array[last]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM