2017-05-29 170 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; 
}