开发者

How to get last key in array in javascript?

开发者 https://www.devze.com 2022-12-18 22:05 出处:网络
This is similar to this question,only PHP->javascript How to get numeric key of new pushed i开发者_运维问答tem in PHP?var foo = myarray[myarray.length - 1];

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

How to get numeric key of new pushed i开发者_运维问答tem 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);
    }
}


I assume your array is a "key associated array" with string keys in number format. You will need to do it in 3 steps:

  1. Get all array keys.
  2. Convert array keys to an integer.
  3. 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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消