简体   繁体   中英

Returning the last element in a array always

I am very new to javascript and I'm just doing little problems that I can find on the web. My question to you guys is their an array method or something that returns the last element in the array. No matter if new elements gets added to the array or not? I know if we had an array like

var array = [1,2,3,4];

You would specify the last one by saying array[3], but if you added a 5 at the end of the array do I have to go back in the code and change the array[3] to array[4]? Or is there a way to code it from the beginning to know when new elements get added?

Thanks.

The .length property usually(*) returns the number of elements in the array. Subtract 1 and you get the highest index in the array.

var lastElement = array[array.length - 1];

(*): Arrays can have "holes" which can make things a bit more complicated, but you don't have to worry about that in 99%(**) of all cases.

(**): That's a guess.

Another method you can use is .slice

var lastElement = array.slice(-1)[0];

.slice returns an array containing select elements of another array, without modifying the original.

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM