我有一个像这样的数组:
array = [1,2,3,4,5,6,7,8]
我想删除最后4个值,使得数组变为:array = [1,2,3,4]。我使用了array.splice(array.length - 4, 1)但是没有起作用。有什么想法吗?
我有一个像这样的数组:
array = [1,2,3,4,5,6,7,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; }
var myList = [1,2,3,4,5,6,7,8];
var removed = myList.splice(-myList.length-4, 4);
let a = [1,2,3,4,5,6,7,8];
a.length -= 4 // delete 4 items from the end
array.splice(0,4)
将从数组开头删除0个元素,并从数组末尾删除4个元素
你也可以使用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);