Get the last item in an array

2018-12-31 14:16发布

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.

30条回答
ら面具成の殇う
2楼-- · 2018-12-31 14:42

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.

查看更多
春风洒进眼中
3楼-- · 2018-12-31 14:43
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.

查看更多
栀子花@的思念
4楼-- · 2018-12-31 14:43

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.

查看更多
妖精总统
5楼-- · 2018-12-31 14:43

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.

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 14:43

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.

查看更多
裙下三千臣
7楼-- · 2018-12-31 14:46

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".
查看更多
登录 后发表回答