2016-05-16 81 views
1

我有一個用戶數組。indexOf用於不同對象的數組

當我點擊按鈕「新增」,我想新的對象添加到這個陣列只有doen't存在則有:

var newUser = { 'creating': true, 'editMode': true }; 
if ($scope.users.indexOf(newUser) < 0) { 
    $scope.users.push(newUser); 
} 

indexOf總是返回-1

這是因爲數組包含「不同」的對象?

enter image description here

+1

您需要用不同的方法識別用戶,例如使用ID進行檢查。如果'newUser'不是*相同的對象*,那麼您總是會得到'-1' –

+0

兩個不同的對象不能相等。 – Jai

+0

'Array.prototype.findIndex()' – Redu

回答

1

我每次要調用「新增」,它會工作(硬而不更多的代碼來表示)時間假設。原因很簡單,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 

如果要檢查,例如,你將不得不作出一個屬性的檢查(姓名,身份證,...)

0

如果你想有一個收集的獨特值你應該使用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; 
 
})();

相關問題