Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 具有不同对象的数组的indexOf_Javascript_Arrays_Angularjs_Indexof - Fatal编程技术网

Javascript 具有不同对象的数组的indexOf

Javascript 具有不同对象的数组的indexOf,javascript,arrays,angularjs,indexof,Javascript,Arrays,Angularjs,Indexof,我有一组用户 当我单击按钮“添加新对象”时,我只想在该数组中不存在新对象时将其添加到该数组中: var newUser = { 'creating': true, 'editMode': true }; if ($scope.users.indexOf(newUser) < 0) { $scope.users.push(newUser); } var newUser={'creating':true,'editMode':true}; if($scope.users.indexO

我有一组用户

当我单击按钮“添加新对象”时,我只想在该数组中不存在新对象时将其添加到该数组中:

var newUser = { 'creating': true, 'editMode': true };
if ($scope.users.indexOf(newUser) < 0) {
    $scope.users.push(newUser);
}
var newUser={'creating':true,'editMode':true};
if($scope.users.indexOf(newUser)<0){
$scope.users.push(newUser);
}
但是
indexOf
总是返回
-1

这是因为数组包含“不同”的对象吗


我想每次您要调用“AddNew”时,它都会起作用(如果没有更多的代码,很难说)。原因很简单,
newUser
的每个实例都是不同的

indexOf
调用检查
newUser
的这个实例。它不检查属性值,只是为了引用实例

e、 g:

var user = {a : "b"};
var users = [];
users.push(user);
users.indexOf(user); // returns 0, reference the user created at the top, inserted beforehand
user = {a : "b"};
users.indexOf(user); // returns -1, reference the user created just above, not yet inserted
例如,如果要检查,则必须检查属性(名称、id等)

如果要拥有应使用的唯一值集合

如果您需要保留传统,否则,您需要使用阵列

var Set=(函数(){
函数集(){}
Set.prototype.has=函数(val){
return!!this.\u list.filter(i=>i.id==val.id).length;
};
Set.prototype.get=函数(val){
如果(!val){
返回此。\u列表;
}
返回此.u list.filter(i=>i.id==val.id).pop();
};
Set.prototype.add=函数(val){
如果(!this.has(val)){
此._列表推送(val)
}
归还这个;
}
返回集;

})();
您需要使用不同的方法来识别用户,如使用id检查。如果
新用户
不是同一个对象,则您得到的总是
-1
两个不同的对象不能相等。
数组.prototype.findIndex()