gpt4 book ai didi

javascript - 从数组末尾删除第 n 个元素

转载 作者:行者123 更新时间:2023-12-05 00:48:43 25 4
gpt4 key购买 nike

我有一个这样的数组:

array = [1,2,3,4,5,6,7,8]

并且我想删除例如最后 4 个值,以便我的数组变成这样:数组 = [1,2,3,4]我使用了 array.splice(array.length - 4, 1) 但它不起作用。有什么想法吗?

最佳答案

你可以使用slice函数如下:

.slice(0, -4)

这种方法不会修改原来的Array

//                                    +---- From 0 to the index = (length - 1) - 4,
// | in this case index 3.
// vvvvv
var array = [1,2,3,4,5,6,7,8].slice(0, -4);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

这种方式修改了原来的Array

var originalArr = [1, 2, 3, 4, 5, 6, 7, 8];

// +---- Is optional, for your case will remove
// | the elements ahead from index 4.
// v
originalArr.splice(-4, 4);
console.log(originalArr);

//----------------------------------------------------------------------

originalArr = [1, 2, 3, 4, 5, 6, 7, 8];
// +---- Omitting the second param.
// |
// v
originalArr.splice(-4);
console.log(originalArr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

文档

关于javascript - 从数组末尾删除第 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49159378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com