正在尝试测试数组中是否存在项,并更新数组

Trying to test whether an item exists in the array or not and updating the array

本文关键字:数组 存在 更新 是否 测试      更新时间:2023-09-26

我要做的是:toggleStar是一个函数,用于从JSON对象列表中选择一个项目,并将其添加到另一个列表(即收藏夹列表)

在这里,我尝试过使用indexOf,尽管它似乎不起作用!

任何建议/帮助都将是美妙的!

提前感谢!

$scope.favlist = JSON.parse($window.localStorage.getItem("favlist"));
    console.log($scope.favlist);
$scope.toggleStar = function(item) {
      item.star = !item.star;
      console.log(item);
         var favlistcontent = $window.localStorage.getItem("favlist");
         if(typeof favlistcontent !== 'string'){
           $scope.favlist = [];
           $window.localStorage.setItem("favlist",JSON.stringify($scope.favlist));
         }
         $scope.favlist = JSON.parse($window.localStorage.getItem("favlist"));
         if( $scope.favlist.indexOf(item) === -1 ) {
         $scope.favlist.push(item);
         $window.localStorage.setItem("favlist",JSON.stringify($scope.favlist));
       } else if( $scope.favlist.indexOf(item) > -1 ){
        console.log("item already exist");
      }
  }

indexOf()只有在数组包含相同对象引用时才能工作。

由于您正在搜索的数组只是从json字符串创建的,因此它所包含的与您的项目匹配的对象不是同一个引用。

您需要遍历数组并比较ID或其他唯一标识符,以找到匹配的项目

简单示例:

var arr =[{foo:"bar"}];
var b = {foo:"bar"};
arr.indexOf(b); // -1 since it isn't the same object reference

var arr2 = []
var x= {foo:"bar"};
arr.push(x);
arr.indexOf(x); // 0 since it is the same object reference

此外,您还可以使用angular.equals()来检查迭代中的匹配,但在进行比较

之前,您不需要更改item.star