具有不同对象的数组的 indexOf
indexOf for array with different objects
我有一组用户。
当我单击按钮 "Add New" 时,我只想向该数组添加新对象,前提是该数组不存在该对象:
var newUser = { 'creating': true, 'editMode': true };
if ($scope.users.indexOf(newUser) < 0) {
$scope.users.push(newUser);
}
但 indexOf
总是 return -1
.
这是因为数组包含 "different" 个对象吗?
我想每次您要调用 "Add New" 时,它都会起作用(如果没有更多代码很难说)。原因很简单,newUser
的每个实例都是不同的。
indexOf
调用会检查 newUser
的这个实例。它不检查 属性 值,只是为了引用实例。
例如:
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
例如,如果你想检查,你必须检查 属性 (name, id, ...)
如果您想要 唯一值集合,您应该使用 ECMASCRIPT-6 Set
如果您需要保留旧版,否则,您需要使用数组...
var Set = (function() {
function Set() {}
Set.prototype.has = function(val) {
return !!this._list.filter(i => i.id === val.id).length;
};
Set.prototype.get = function(val) {
if(!val) {
return this._list;
}
return this._list.filter(i => i.id === val.id).pop();
};
Set.prototype.add = function(val) {
if(!this.has(val)) {
this._list.push(val)
}
return this;
}
return Set;
})();
我有一组用户。
当我单击按钮 "Add New" 时,我只想向该数组添加新对象,前提是该数组不存在该对象:
var newUser = { 'creating': true, 'editMode': true };
if ($scope.users.indexOf(newUser) < 0) {
$scope.users.push(newUser);
}
但 indexOf
总是 return -1
.
这是因为数组包含 "different" 个对象吗?
我想每次您要调用 "Add New" 时,它都会起作用(如果没有更多代码很难说)。原因很简单,newUser
的每个实例都是不同的。
indexOf
调用会检查 newUser
的这个实例。它不检查 属性 值,只是为了引用实例。
例如:
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
例如,如果你想检查,你必须检查 属性 (name, id, ...)
如果您想要 唯一值集合,您应该使用 ECMASCRIPT-6 Set
如果您需要保留旧版,否则,您需要使用数组...
var Set = (function() {
function Set() {}
Set.prototype.has = function(val) {
return !!this._list.filter(i => i.id === val.id).length;
};
Set.prototype.get = function(val) {
if(!val) {
return this._list;
}
return this._list.filter(i => i.id === val.id).pop();
};
Set.prototype.add = function(val) {
if(!this.has(val)) {
this._list.push(val)
}
return this;
}
return Set;
})();