如何删除与数组键相关的元素

How to remove the element with respect to array key?

本文关键字:元素 数组 何删除 删除      更新时间:2023-09-26

我有一个javascript数组,如下所示:

$scope.products = [
    {id:'1', name:'IPhone6', price: '1,000 AED', quantity: '2'},
    {id:'2', name:'Samsung Mini', price: '750 AED', quantity: '1'},
    {id:'3', name:'Dell Laptop', price: '1700 AED', quantity: '3'},
    {id:'4', name:'HCL Monitor 7"', price: '650 AED', quantity: '7'},
];

使用ng-repeat Angular js 函数显示上面的数组。

我正在调用一个删除函数并将id作为参数传递。如何从数组中删除特定元素?

$scope.products.slice($id, 1)不是必需的。我必须删除有关 id 的内容?请指教。

这应该有效:

// id = '3'
$scope.products = $scope.products.filter(function (p) { return p.id !== id });

签出拼接方法

  1. Array.prototype.splice
  2. W3学校 - 拼接

您可能希望将提供的带有 id 的元素的索引传递给 remove 函数,为此,您可以描述 getIndexBy 函数

Array.prototype.getIndexBy = function (name, value) {
    for (var i = 0; i < this.length; i++) {
        if (this[i][name] == value) {
            return i;
        }
    }
}

并像使用它一样使用

index=products.getIndexBy("id", 3) 

其中 3 是您提供的 ID。然后,可以在拼接方法中使用此索引来删除特定元素。

假设您希望按索引删除元素。

这样在点击操作中使用$index

ng-click='slice($index);'

和你的函数像这样

$scope.slice = function(element){
    $scope.friends.splice(element, 1);
}

或者通过此示例:

网页代码

<ul>
   <li ng-repeat="product in products" ng-click='slice($index);'>
      [{{$index + 1}}] {{product.name}}
    </li>
</ul>

脚本代码

$scope.products = [
                    {id:'1', name:'IPhone6', price: '1,000 AED', quantity: '2'},
                    {id:'2', name:'Samsung Mini', price: '750 AED', quantity: '1'},
                    {id:'3', name:'Dell Laptop', price: '1700 AED', quantity: '3'},
                    {id:'4', name:'HCL Monitor 7"', price: '650 AED', quantity: '7'},
                  ];
$scope.slice = function(element){
     $scope.friends.splice(element, 1);
}

您可以定义一个实用程序函数:

(function(window) {
      var utility = window.utility|| (window.utility= {});
      function remove(items, fn) {           
           var toRemove = [];          
           angular.forEach(items, function(item, i) {  
               if (fn(item)) {
                  toRemove.push(i);
               }
            });
            angular.forEach(toRemove, function(index) {
                items.splice(index,1);
            });
      }
     angular.extend(utility, {
         'remove': remove
     });
})(window);

若要使用此函数,请将项数组作为第一个参数传递,将谓词函数作为第二个参数传递。谓词返回 true 的所有项目都将从数组中删除该项目:

例子:

要删除名称为"john"的所有用户,请执行以下操作:

utility.remove($scope.users, function(user) {
    return user.name == 'john';
});

要删除 ID 为 3 的用户,请执行以下操作:

utility.remove($scope.users, function(user) {
    return user.id == 3;
});