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

use*_*203 1 javascript arrays

我有一个这样的数组:

array = [1,2,3,4,5,6,7,8]
Run Code Online (Sandbox Code Playgroud)

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

Ele*_*Ele 5

您可以slice按如下方式使用该功能:

.slice(0, -4)
Run Code Online (Sandbox Code Playgroud)

这种方法不会修改原始数组

.slice(0, -4)
Run Code Online (Sandbox Code Playgroud)
//                                    +---- 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);
Run Code Online (Sandbox Code Playgroud)

这种方法修改了原始数组

.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)

文档