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

4

我有一个像这样的数组:

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

我想删除最后4个值,使得数组变为:array = [1,2,3,4]。我使用了array.splice(array.length - 4, 1)但是没有起作用。有什么想法吗?

可能是重复问题 https://dev59.com/Zmsz5IYBdhLWcg3w9s2r - Doug Clark
5个回答

8

您可以按以下方式使用函数slice

.slice(0, -4)

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

//                                    +---- 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; }

这种方法修改了原始数组

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; }

Docs


2

1
您可以使用length属性。
let a = [1,2,3,4,5,6,7,8];

a.length -= 4 // delete 4 items from the end

0
array.splice(0,4)

将从数组开头删除0个元素,并从数组末尾删除4个元素


0

你也可以使用filter来删除元素(它不会修改现有的数组)

array = [1,2,3,4,5,6,7,8];
array1=array.filter((x,i)=>i<array.length-4);
console.log(array1);

或者你可以使用splice(它会改变数组本身)

array = [1,2,3,4,5,6,7,8];
array.splice(-4);
console.log(array);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接