2017-05-29 64 views
0

我有一個placeCollection集合,它有一個名爲locFrnd的數組。 由於我無法使用函數locFrnd對象數組,我將它移動到名爲dup的新數組。作爲dup的主要目的是我可以使用這些數據並獲得indexOf函數。 $scope.Friend是傳入的數據源,也是一個數組。用戶可以在$scope.Friend中發送多個值。我想在這裏檢查的主要邏輯是,如果在$scope.Friend中有兩個值作爲$scope.Friend中的用戶輸入,則需要在locFrnd數組中逐個檢查這兩個值。如果它們不存在,則它們需要在locFrnd數組中被推入。唯一的挑戰是indexOf操作是指最後一個值dup。 e.g dupr,j$scope.Friendr,jjdup$scope.Friend相比r和未來價值也沒有得到確認。我不知道爲什麼這種匿名行爲發生在indexOf功能的情況下indexOf即使數組中存在值,也返回-1的數組

//if country exist 
else if (cnt_exist == 1) { 
    alert("country exist"); 

    var len = $scope.placeCollection[cnt_i].locFrnd.length; 
    for (var j = 0; j < len; j++) { 
     var dup = []; 
     dup[j] = $scope.placeCollection[cnt_i].locFrnd[j].name; 
    } 

    //check for friend now 
    alert("checking for friend"); 

    //some code has to inserted here to handle Friends as it is an array 
    alert($scope.Friend.length); 

    for (var k = 0; k < $scope.Friend.length; k++) { 
     var frnd_exist = 0; 

     alert($scope.Friend[k]); 
     alert(dup.indexOf($scope.Friend[k])); 

     if (dup.indexOf($scope.Friend[k]) != -1) // friend exist 
     { 
      alert("entered friend comparison"); 
      frnd_exist = 1; 
     } 

     if (frnd_exist == 1) // if friend does not exist 
     { 
      alert("friend exist"); 
     } else if (frnd_exist == 0) { 
      var eachFriend = { 
       name: $scope.Friend[k] 
      } 

      $scope.placeCollection[cnt_i].locFrnd.push(eachFriend); 
     } 
    } 
+0

這個statment外面總是返回除-1值,如果(dup.indexOf($ scope.Friend [K])!= -1)//朋友存在 – Arunroy

+0

你嘗試打印'$範圍。朋友[k]'或試過做 'var friend = $ scope.Friend [k]; if(dup.indexOf(friend)!= -1)'?? –

+0

應該沒有問題,但嘗試'if(dup.indexOf($ scope.Friend [k])> -1)'也 –

回答

0

答案很簡單。

在for循環的每次迭代中,您正在初始化dup。初始化循環

var dup = []; 
for (var j = 0; j < len; j++) { 
    dup[j] = $scope.placeCollection[cnt_i].locFrnd[j].name; 
}