js five ways to get the last element of the array, and replace the last element of the array

1. Using length

let arr=[1,2,3];
arr[arr.length-1] //3
1
2

2. The array pop method, deleting the last bit of the array and returning it will modify the original array

let arr=[1,2,3];
arr.pop() //3
1
2

3. The array slice method, the return value is a new array containing the last element

let arr=[1,2,3];
arr.slice(-1) //[3]
1
2

4. Array at method (new feature of ES2022)

let arr=[1,2,3];
arr.at(-1) //3
1
2

5. The array reverse() method can be used to reverse the order of the elements in the array, and the front element will become the last element. (Thank you big brother)

 let arr = [1,2,3] 
 arr.reverse()[0]
1
2

Replace the last bit of data in the array

var d = [1,2,3,4,5,6,7];
var tihuan = 'abcd'
var cc= d[d.length - 1]; 

d = d.slice(0,-1); // 截取掉数组内最后一位数值,剩余数组 再次赋值给y轴    slice方法不会改变原始数组
console.log(d) // [1,2,3,4,5,6]
d.push(tihuan);
console.log(d) // [1,2,3,4,5,6,'abcd']

Guess you like

Origin blog.csdn.net/Maxueyingying/article/details/130683911