This is similar to this question,only PHP->javascript
How to get numeric key of new pushed item in PHP?
The end() function is an inbuilt function in PHP and is used to find the last element of the given array. The end() function changes the internal pointer of an array to point to the last element and returns the value of the last element.
To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array.
The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].
To get the last item in an object, use the Object. keys() method to get an array of the object's keys and call the pop() method on the result, e.g. Object. keys(obj). pop() .
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);
}
}
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