我想做的是: 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
关于javascript - 尝试测试数组中是否存在某个项目并更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34602687/