如何用javascript从数组中删除项?我想要一个类似拉的东西来做与推相反的事情

How can I remove items from an array in javascript ? I want something like a pull to do the opposite of push

本文关键字:一个 删除 数组 何用 javascript 我想要      更新时间:2023-12-27

我希望我的应用程序在屏幕上有一个跟踪活动的区域。

我创建了以下内容:

$scope.activity = [];

我想的是,当某个东西开始时,我会像这样推到这个数组上:

$scope.activity.push("Loading content 1");
$scope.activity.push("Loading content 2");
$scope.activity.push("Loading content 3");
$scope.activity.push("Loading content 4");

然后,我可以在屏幕上有一个区域,显示正在发生的事情,用ng重复显示数组中的所有内容:

<div ng-repeat="row in activity">
    {{ row }}
<div>

我的问题是,我不确定一旦活动完成,如何从数组中删除项目。有人能给我一个如何做这件事的建议吗。我真正需要的是某种pull函数,在这里我可以指定我推送的内容的名称并将其删除。类似于:

 $scope.activity.pull("Loading content 4");

此外,我还需要另一个功能,如:

 $scope.activity.update("Loading content 4", status);

我正在寻找一个不使用jQuery或下划线的解决方案。我的用户是IE9及以上。

使用阵列拼接方法:

更改数组的内容,添加新元素,同时删除旧元素。

您可以这样做:

var activityArray = [];
activityArray.push("Loading content 1");
activityArray.push("Loading content 2");
activityArray.push("Loading content 3");
activityArray.push("Loading content 4");
//find the item we want to delete
var index = activityArray.indexOf('Loading content 4');// returns 3
activityArray.splice(index,1)//remove the item at index 3

.pop().shift()经常与.push()一起使用。