在Javascript中使用splice删除对象数组中某个位置后的所有元素

Remove all elements after a position in an array of objects in Javascript using splice

本文关键字:位置 元素 数组 Javascript splice 对象 删除      更新时间:2023-09-26

我想知道是否有一种简单的方法可以在关键位置后拼接出所有元素。

array.splice(index,howmany,item1,.....,itemX)

文档说指定要删除的元素数量的第二个元素是必填字段,完成此操作是否有警告?

p。S -不寻找正常的暴力解决方案

我想知道是否有一种简单的方法可以在json数组中的关键位置后拼接出所有元素。

如果关键位置后的所有元素都是,则执行以下操作:

array.length = theKeyPosition;

例如:

var array = [
    "one",
    "two",
    "three",
    "four",
    "five",
    "six"
];
var theKeyPosition = 3;
array.length = theKeyPosition; // Remove all elements starting with "four"

如果您还不知道关键位置,在ES5环境中(这可以被模糊),您可以使用filter:

var array = [
    "one",
    "two",
    "three",
    "four",
    "five",
    "six"
];
var keep = true;
array = array.filter(function(entry) {
    if (entry === "four") {
        keep = false;
    }
    return keep;
});

这是使用字符串,但您可以轻松地将if (entry === "four") {更改为if (entry.someProperty === someValue) {为您的对象数组。

对于Array.prototype.splice(),第二个参数实际上是可选的,并且仅使用第一个参数就可以实现所需的行为。

例如(从接受的答案中复制):

const array = [
    "one",
    "two",
    "three",
    "four",
    "five",
    "six"
];
const theKeyPosition = 3;
array.splice(theKeyPosition+1); // Remove all elements starting with "four"
console.log(array);

然而,我仍然喜欢设置长度属性,因为它应该更快(我找不到JSPerf结果,请在这里帮助我)。

在MDN或我对类似问题的其他回答上阅读更多相关内容。