Getting the last element of a javascript array

I am trying to get the last element of an array after doing split on a string using javascript.

var str ="Watch-The-Crap-456".split('-')[this.length]; console.log(str);​​​ // want it to console log 456, now it consoles WATCH which is in array[0] 

I tried to do [this.length - 1] to get the last element of the array, but it gives me undefined, I know that some of you can say that they create another variable to store the array, but it's interesting to see if we can keep things in short.

+7
source share
4 answers

What about:

 "Watch-The-Crap-456".split('-').pop(); // returns 456 
+23
source

this defined depending (or at least not referenced by an array).

A naive way could be two lines:

 var str ="Watch-The-Crap-456".split('-'); console.log(str[str.length - 1]);​​​ 

See in action .

+2
source

Do you need only the last item ? You can do it:

 var str ="Watch-The-Crap-456"; console.log(str.slice(str.lastIndexOf('-')+1));​ 

In this case, you must first define your string, which makes sense. I don’t see a situation where you would like to get the last element from a string literal, you simply write str = "456" and do with it.

+1
source

Using underscores, which is part of some other libraries / frameworks such as Backbone.js:

 _.last(str.split('-')); 

See: http://underscorejs.org/#last

0
source

All Articles