【问题标题】:Java Script array.indexOf is not working [duplicate]Javascript array.indexOf 不起作用[重复]
【发布时间】:2016-10-23 02:03:07
【问题描述】:

这很令人惊讶,但简单的函数 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 但我完全确定该项目存在于数组中。这里有什么问题?

【问题讨论】:

  • 不,该对象不存在:“名称”与 item.Name 相同的对象存在,这是非常不同的。
  • 好吧,但是 item.Name 只是字符串,不是吗?
  • 您在对象数组中搜索字符串,它如何知道您要匹配 .Name 属性?
  • 你试过在控制台中调试这个吗?如果在第 211 行设置断点,就可以在控制台执行 JS。这将是调试问题的最快方法。

标签: javascript angularjs


【解决方案1】:

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

product.indexOf(item.Name);

您应该运行:

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

这将返回与您的值匹配的数组

【讨论】:

  • map 会更合适,因为 OP 需要索引。例如:var index = product.map(function(p) { return p.Name; }).indexOf(item.Name);
  • @OscarBarrett,是的,这正是我所需要的。请添加评论作为答案。
  • @asdf_enel_hak,是的,您的解决方案有效,但这不是我需要的。
  • @andrey.shedko 是的,我明白了
  • @andrey.shedko 我会添加我的评论作为答案,但是这个问题已被标记为重复,因此被锁定。
猜你喜欢
  • 1970-01-01
  • 2015-09-01
  • 2014-04-22
  • 2010-12-22
  • 2013-11-19
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多