Javascript 返回-1的数组索引,即使该值存在于数组中
我有一个Javascript 返回-1的数组索引,即使该值存在于数组中,javascript,angularjs,arrays,Javascript,Angularjs,Arrays,我有一个placeCollection集合,它有一个名为locFrnd的数组。 由于无法在对象的locFrnd数组上使用indexOf函数,我将其移动到名为dup的新数组中。由于dup的主要目的是我可以使用数据并获得对其执行的indexOf函数$scope.Friend是传入的数据源,也是一个数组。用户可以在$scope.Friend中发送多个值。我想在这里检查的主要逻辑是,如果在$scope.Friend中有两个值作为用户输入,则需要在locFrnd数组中逐个检查这两个值。如果它们不存在,则需
placeCollection
集合,它有一个名为locFrnd
的数组。
由于无法在对象的locFrnd
数组上使用indexOf
函数,我将其移动到名为dup
的新数组中。由于dup
的主要目的是我可以使用数据并获得对其执行的indexOf
函数$scope.Friend
是传入的数据源,也是一个数组。用户可以在$scope.Friend
中发送多个值。我想在这里检查的主要逻辑是,如果在$scope.Friend
中有两个值作为用户输入,则需要在locFrnd
数组中逐个检查这两个值。如果它们不存在,则需要将它们推入locFrnd
数组。唯一的挑战是indexOf
操作引用的是dup
的最后一个值。e、 gdup
具有r,j
和$scope。Friend
具有r,j
来自dup
的j
与来自$scope的r
进行比较。Friend
也不会检查下一个值。我不确定在indexOf
函数的情况下为什么会发生这种匿名行为
//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);
}
}
//如果国家/地区存在
else if(cnt_exist==1){
警报(“国家存在”);
var len=$scope.placeCollection[cnt_i].locFrnd.length;
对于(var j=0;j
答案很简单
在for循环的每次迭代中,您都在初始化dup
。在循环外初始化
var dup = [];
for (var j = 0; j < len; j++) {
dup[j] = $scope.placeCollection[cnt_i].locFrnd[j].name;
}
var-dup=[];
对于(var j=0;j
此语句始终返回除-1 if(dup.indexOf($scope.Friend[k])!=-1)之外的值//好友存在您是否尝试打印$scope.Friend[k]
或尝试执行var-Friend=$scope.Friend[k];if(dup.indexOf(Friend)!=-1)
应该不重要,但尝试if(dup.indexOf($scope.Friend[k>)-1)
also@SyamPillai问题不在于$scope.Friend,因为我正在比较前的警报中打印它。问题在于dup数组,因为它只引用了中的最后一个值it@SyamPillai我正在打印此值dup.indexOf($scope.Friend[k])在alert中也是如此,除了少数情况外,即使值存在于dup中,它也不会成为-1