2016-06-21 107 views
0

这是令人惊讶的,但简单的函数array.IndexOf不工作。Java脚本array.indexOf不工作

$scope.nextProduct = function (pos, item) { 
    switch (pos) { 
     case 0: product = $scope.Menu[0].Breakfast 
      break 
     case 1: product = $scope.Menu[0].Lunch 
      break 
     case 2: product = $scope.Menu[0].BeforTraining 
      break 
     case 3: product = $scope.Menu[0].AfterTraining 
      break 
     case 4: product = $scope.Menu[0].Dinner 
      break 
     default: product = $scope.Menu[0].Breakfast 
      break 
    } 
    var index = product.indexOf(item.Name); 
    product[index - 1].IsSelect = false; 
    product[index + 1].IsSelected = true; 
} 

indexOf返回-1但我完全确定该项存在于数组中。这里有什么可能是错的? enter image description here

+0

没有,对象不存在:一个对象,其“名”是一样的item.Name存在,这是非常不同的。 –

+0

好吧,但item.Name它只是字符串,不是吗? –

+2

您在一个字符串中搜索对象数组,它如何知道您想匹配.Name属性? –

回答

2

通过这个表达式,您正在搜索对象数组中的字符串。

product.indexOf(item.Name); 

相反,你应该运行:

var res = product.filter(function(elem){ 
    return elem.Name == someValue 
}) 

这将返回数组匹配你的价值

+1

由于OP需要索引,'map'会更合适。例如:'var index = product.map(function(p){return p.Name;})。indexOf(item.Name);' –

+0

@OscarBarrett,是的,这正是我需要的。请添加评论作为答案。 –

+0

@asdf_enel_hak,是的,你的解决方案正在工作,但这不是我需要的。 –