Get the last item in an array

2018-12-31 13:59发布

问题:

Here is my JavaScript code so far:

var linkElement = document.getElementById(\"BackButton\");
var loc_array = document.location.href.split(\'/\');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); 
linkElement.appendChild(newT);

Currently it takes the second to last item in the array from the URL. However I want to do a check for the last item in the array to be \"index.html\" and if so, grab the third to last item instead.

回答1:

if(loc_array[loc_array.length-1] == \'index.html\'){
 //do something
}else{
 //something else.
}

In the event that your server serves the same file for \"index.html\" and \"inDEX.htML\" you can also use: .toLowerCase().

Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.



回答2:

Not sure if there\'s a drawback, but this seems quite concise:

arr.slice(-1)[0] 

or

arr.slice(-1).pop()

Both will return undefined if the array is empty.



回答3:

Use Array.pop:

var lastItem = anArray.pop();

Important : This returns the last element and removes it from the array



回答4:

A shorter version of what @chaiguy posted:

Array.prototype.last = function() {
    return this[this.length - 1];
}

Reading the -1 index returns undefined already.

EDIT:

These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.

export function last(array) {
    return array[array.length - 1];
}


回答5:

Two options are:

var last = arr[arr.length - 1]

or

var last = arr.slice(-1)[0]

The former is faster, but the latter looks nicer

http://jsperf.com/slice-vs-length-1-arr



回答6:

Here\'s how to get it with no effect on the original ARRAY

a = [1,2,5,6,1,874,98,\"abc\"];
a.length; //returns 8 elements

If you use pop(), it will modify your array

a.pop();  // will return \"abc\" AND REMOVES IT from the array 
a.length; // returns 7

But you can use this so it has no effect on the original array:

a.slice(-1).pop(); // will return \"abc\" won\'t do modify the array 
                   // because slice creates a new array object 
a.length;          // returns 8; no modification and you\'ve got you last element 


回答7:

I\'d rather use array.pop() than indexes.

while(loc_array.pop()!= \"index.html\"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));

this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You\'ll lose the last elements from the array, though.



回答8:

The \"cleanest\" ES6 way (IMO) would be:

const foo = [1,2,3,4];
const bar = [...foo].pop();

This avoids mutating foo, as .pop() would had, if we didn\'t used the spread operator.
That said, I like aswell the foo.slice(-1)[0] solution.



回答9:

Getting the last item of an array can be achieved by using the slice method with negative values.

You can read more about it here at the bottom.

var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == \"index.html\")
{
  //your code...
}

Using pop() will change your array, which is not always a good idea.



回答10:

You can use this pattern...

let [last] = arr.slice(-1);

While it reads rather nicely, keep in mind it creates a new array so it\'s less efficient than other solutions but it\'ll almost never be the performance bottleneck of your application.



回答11:

If one wants to get the last element in one go, he/she may use Array#splice():

lastElement = document.location.href.split(\'/\').splice(-1,1);

Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.

Note: This changes the original array by removing its last element. Think of splice(-1,1) as a pop() function that pops the last element.



回答12:

jQuery solves this neatly:

> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined


回答13:

For those not afraid to overload the Array prototype (and with enumeration masking you shouldn\'t be):

Object.defineProperty( Array.prototype, \"getLast\", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        return this[ this.length - 1 ];
    }
} );


回答14:

I generally use underscorejs, with it you can just do

if (_.last(loc_array) === \'index.html\'){
  etc...
}

For me that is more semantic than loc_array.slice(-1)[0]



回答15:

I think if you only want get the element without remove, is more simple use this:

arr.slice(-1)

by the way... i didnt check performance, but i think is more simple and clean to write



回答16:

This question has been around a long time, so I\'m surprised that no one mentioned just putting the last element back on after a pop().

arr.pop() is exactly as efficient as arr[arr.length-1], and both are the same speed as arr.push().

Therefore, you can get away with:

let thePop = arr.pop()
arr.push(thePop)

Which can be reduced to this (same speed):

arr.push(thePop = arr.pop())

This is twice as slow as arr[arr.length-1], but you don\'t have to stuff around with an index. That\'s worth gold on any day.

Of the solutions I\'ve tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]:

[Method]..............[ETUs 5 elems]...[ETU 1 million elems]

arr[arr.length - 1]      ------> 1              -----> 1

let myPop = arr.pop()
arr.push(myPop)          ------> 2              -----> 2

arr.slice(-1).pop()      ------> 36             -----> 924  

arr.slice(-1)[0]         ------> 36             -----> 924  

[...arr].pop()           ------> 120            -----> ~21,000,000 :)

The last three options, ESPECIALLY [...arr].pop(), get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop() probably maintains something like it\'s 120:1 ratio. Still, no one likes a resource hog.



回答17:

Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you\'re working with nested arrays.

var array = [[1,2,3], [4,5,6], [7,8,9]]
​
array.slice(-1)[0]
​
//instead of 
​
array[array.length-1]
​
//Much easier to read with nested arrays
​
array.slice(-1)[0].slice(-1)[0]
​
//instead of
​
array[array.length-1][array[array.length-1].length-1]


回答18:

You can add a last() function to the Array prototype.

Array.prototype.last = function () {
    return this[this.length - 1];
};


回答19:

You could add a new property getter to the prototype of Array so that it is accessible through all instances of Array.

Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (this[this.length - 1]).

Finally you wrap it in a condition that checks whether the last-property is still undefined (not defined by another script that might rely on it).

if(typeof Array.prototype.last === \'undefined\') {
    Object.defineProperty(Array.prototype, \'last\', {
        get : function() {
            return this[this.length - 1];
        }
    });
}

// Now you can access it like
[1, 2, 3].last;            // => 3
// or
var test = [50, 1000];
alert(test.last);          // Says \'1000\'

Does not work in IE ≤ 8.



回答20:

const lastElement = myArray[myArray.length - 1];

This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).



回答21:

EDITED:

Recently I came up with one more solution which I now think is the best for my needs:

function w (anArray)
{ return (
  { last() {return anArray [anArray.length - 1]
  }
}        );

With the above definition in effect I can now say:

let last = w ([1,2,3]).last();
console.log(last) ; // -> 3

The name \"w\" stands for \"wrapper\". You can see how you could easily add more methods besides \'last()\' to this wrapper.

I say \"best for my needs\", because this allows me to easily add other such \"helper methods\" to any JavaScript built-in type. What comes to mind are the car() and cdr() of Lisp for instance.



回答22:

I think the easiest and super inefficient way is:

var array = [\'fenerbahce\',\'arsenal\',\'milan\'];
var reversed_array = array.reverse(); //inverts array [milan,arsenal,fenerbahce]
console.log(reversed_array[0]) // result is \"milan\".


回答23:

I\'ll suggest to create helper function and reuse it every time, you\'ll need it. Lets make function more general to be able to get not only last item, but also second from the last and so on.

function last(arr, i) {
    var i = i || 0;
    return arr[arr.length - (1 + i)];
}

Usage is simple

var arr = [1,2,3,4,5];
last(arr);    //5
last(arr, 1); //4
last(arr, 9); //undefined

Now, lets solve the original issue

Grab second to last item form array. If the last item in the loc_array is \"index.html\" grab the third to last item instead.

Next line does the job

last(loc_array, last(loc_array) === \'index.html\' ? 2 : 1);

So, you\'ll need to rewrite

var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); 

in this way

var newT = document.createTextNode(unescape(capWords(last(loc_array, last(loc_array) === \'index.html\' ? 2 : 1)))); 

or use additional variable to increase readability

var nodeName = last(loc_array, last(loc_array) === \'index.html\' ? 2 : 1);
var newT = document.createTextNode(unescape(capWords(nodeName)));


回答24:

Using lodash _.last(array) Gets the last element of array.

data = [1,2,3]
last = _.last(data)
console.log(last)
<script src=\"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js\"></script>



回答25:

In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.

Syntax:

arr.lastItem // get last item
arr.lastItem = \'value\' // set last item

arr.lastIndex // get last index

You can use polyfill.

Proposal author: Keith Cirkel(chai autor)



回答26:

You can achieve this issue also without extracting an array from the url

This is my alternative

var hasIndex = (document.location.href.search(\'index.html\') === -1) ? doSomething() : doSomethingElse();

!Greetings¡



回答27:

Using ES6/ES2015 spread operator (...) you can do the following way.

const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)

Please notice that using spread operator and reverse we did not mutated original array, this is a pure way of getting a last element of the array.



回答28:

The simple way to get last item of array:

var last_item = loc_array.reverse()[0];

Of course, we need to check to make sure array has at least one item first.



回答29:

There is also a npm module, that add last to Array.prototype

npm install array-prototype-last --save

usage

require(\'array-prototype-last\');

[1, 2, 3].last; //=> 3 

[].last; //=> undefined 


回答30:

Another ES6 only option would be to use Array.find(item, index)=> {...}) as follows:

const arr = [1, 2, 3];
const last = arr.find((item, index) => index === arr.length - 1);

little practical value, posted to show that index is also available for your filtering logic.