一个分享WordPress、Zblog、Emlog、Typecho等主流博客的教程网站!
当前位置:网站首页 > 其他相关教程 > 正文

js删除数组最后一个元素

作者:xlnxin发布时间:2023-10-06分类:其他相关教程浏览:248


导读:slice删除123456789vararr=[1,2,3,4,5]varnew_arr=arr.slice(0,-1)//arr=>[1,2,3,4,...

slice 删除

1
2
3
4
5
6
7
8
9
var arr = [1,2,3,4,5]
var new_arr = arr.slice(0, -1)
// arr => [1,2,3,4,5]
// new_arr => [1,2,3,4]
  
var arr = [1,2,3,4,5]
var new_arr = arr.slice(0, arr.length - 1)
// arr => [1,2,3,4,5]
// new_arr => [1,2,3,4]

splice 删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var arr = [1,2,3,4,5]
var new_arr = arr.splice(-1)
// arr => [1,2,3,4]
// new_arr => [5]
  
var arr = [1,2,3,4,5]
var new_arr = arr.splice(-1, 1)
// arr => [1,2,3,4]
// new_arr => [5]
  
var arr = [1,2,3,4,5]
var new_arr = arr.splice(arr.length - 1)
// arr => [1,2,3,4]
// new_arr => [5]
  
var arr = [1,2,3,4,5]
var new_arr = arr.splice(arr.length - 1, 1)
// arr => [1,2,3,4]
// new_arr => [5]

pop 删除

1
2
3
var arr = [1,2,3,4,5]
arr.pop()
// arr => [1,2,3,4]

for 删除

1
2
3
4
5
6
7
8
9
var arr = [1,2,3,4,5]
var new_arr = []
for (let i = 0, len = arr.length; i < len; i++) {
    if (i < len - 1) {
        new_arr.push(arr[i])
    }
}
// arr => [1,2,3,4,5]
// new_arr => [1,2,3,4]

length 删除

1
2
3
var arr = [1,2,3,4,5]
arr.length = arr.length - 1
// arr => [1,2,3,4]


标签:js