current position:Home>JS to get the last element of the array

JS to get the last element of the array

2022-06-24 08:33:28User 2323866

Here is js Three ways to get the last element of an array

One 、JavaScript pop()  Method

pop() Method is used to delete and return the last element of the array . Be careful :pop() Method will delete arrayObject Last element of , Reduce the length of the array by 1, And return the value of the element it deleted . If the array is already empty , be pop() Don't change the array , And back to undefined value .

var arr = new Array("js","JavaScript","jQuery");
 var end = arr.pop()
 console.log(end);//jQuery
 console.log(arr);//["js", "JavaScript"]

Two 、 Array of  length  attribute

var arr = new Array("js","JavaScript","jQuery");
 var end = arr[arr.length-1]
 console.log(end);//jQuery

3、 ... and 、JavaScript slice()  Method

slice() Method to return selected elements from an existing array . But the type of data returned is  array  No  string  Pay attention to this !

var arr = new Array("js","JavaScript","jQuery");
 var end = arr.slice(-1);
 console.log(end);//["jQuery"]

copyright notice
author[User 2323866],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/20210623184251056n.html

Random recommended