Home  >  Article  >  Web Front-end  >  How to delete the last element of javascript array

How to delete the last element of javascript array

青灯夜游
青灯夜游Original
2021-11-25 18:04:346189browse

Delete method: 1. Use the pop() method of Array, the syntax is "array.pop()"; 2. Use the delete operator, the syntax is "delete arr[arr.length-1]"; 3. Use splice() method, syntax "arr.splice(-1,1)".

How to delete the last element of javascript array

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Method 1: Use the pop() method----you can delete an element at the end of the array

array.pop() method can delete the last element in the array element and returns the deleted element.

Let’s take a closer look at the following example:

var arr = [2,4,6,8,10];  //定义数组
arr.pop();
console.log(arr)

How to delete the last element of javascript array

Method 2: Use the delete operator to delete the last element of the array

var arr = [2,4,6,8,10];  //定义数组

var len=arr.length;//计算数组长度
delete arr[len-1];  //删除最后一个元素(数组长度-1)
console.log(arr);

How to delete the last element of javascript array

Method 3: Use splice() method

var arr= [1,2,3,4,5];

//从倒数第二个元素开始,截取两个元素
arr.splice(-1,1);
console.log(arr);

How to delete the last element of javascript array

[Related recommendations :javascript learning tutorial

The above is the detailed content of How to delete the last element of javascript array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn