2015-05-29 30 views
1

我有一个列表的列表,其来自于ajax response服务器具有以下结构:Array.indexOf的名单列表不工作

var mapping = [  //response.mapping 
    ["userOne", 1], 
    ["userTwo", 2], 
    ["userthree", 3], 
    ["userfour", 4], 

    ["personOne", 1], 
    ["personTwo", 2], 
    ["personOne", 3], 
]; 

由于名单是恒定永远,这将有7只元素在任何时候。我想索引它的任何元素来更新一些DOM元素。

// Gives me any of list element which is random elm of the list `mapping`. 
var captured_list_elm = process_mapping_list();  
var status = mapping.indexOf(captured_list_elm);// getting always -1 

在这里我总是得到-1状态。

  • 可能是什么原因?
  • 为什么indexOf无法计算其索引?
  • 找到它的方法是什么,只通过循环列表来获取索引?

创建一个jsFiddle

注意 - 其实这应该是一个JSON,但有人在我们的团队写了它作为一个列表的列表。我现在无法更新它,因为代码正在生产中。

+3

向我们显示:process_mapping_list。 – sirrocco

+0

@sirrocco - 让我添加一个jsfiddle。 – Laxmikant

+0

@sirrocco - 删除该功能,我不认为这是演示所需的。看看[jsFiddle](http://jsfiddle.net/ceham967/)。 – Laxmikant

回答

5

Array.indexOf()使用全等(===)找到一个元素。 mapping的元素是数组,而碰巧具有相同元素的两个不同数组不是===。我怀疑process_mapping_list()将返回一个数组,看起来像mapping的要素之一,但不是元素本身(就像你的小提琴一样)。

您可能需要编写使用自定义相等性测试的自己的查找函数。对于这样的测试,看看this thread。根据您定位的环境,您可以使用findIndex()而不是indexOf()。该功能允许您提供自己的测试功能。

+0

@ TedHopp - 好的,非常感谢。完美回答我的期望。 – Laxmikant

0

这里有一个办法让周围的===问题与的indexOf ...

选项1:

var mapping = [  //response.mapping 
    ["userOne", 1], 
    ["userTwo", 2], 
    ["userthree", 3], 
    ["userfour", 4], 

    ["personOne", 1], 
    ["personTwo", 2], 
    ["personOne", 3], 
]; 

var jsonMapping = []; 
for (var i = 0; i < mapping.length; i++) { 
    jsonMapping.push(JSON.stringify(mapping[i])); 
} 
var captured_list_elm = ["personOne", 1]; 
var status = jsonMapping.indexOf(JSON.stringify(captured_list_elm)); 
alert("status= "+status); 

选项2

var mapping = [  //response.mapping 
    ["userOne", 1], 
    ["userTwo", 2], 
    ["userthree", 3], 
    ["userfour", 4], 

    ["personOne", 1], 
    ["personTwo", 2], 
    ["personOne", 3], 
]; 
var findIndex = function (hayStack, needle) { 
    for (var i = 0; i < hayStack.length; i++) { 
     if(hayStack[i][0] === needle[0] && hayStack[i][1] === needle[1]) { 
      return i; 
     } 
    } 
    return -1; 
}; 
var captured_list_elm = ["personOne", 1]; 
var status = findIndex(mapping, captured_list_elm); 
alert("status= "+status); 
+0

老实说,这有点讨厌..转换为JSON查找?没有... – sirrocco

0

要确认答案@泰德 - 霍普给我你的分叉和的jsfiddle它slightly modified。基本上我所做的就是将变量captured_list_elm移动到顶部,并将其作为值添加到数组中。正如你可以看到现在Array.indexOf返回4这是正确的(从零开始)指数:

var captured_list_elm = ["personOne", 1]; 

var mapping = [  //response.mapping 
    ["userOne", 1], 
    ["userTwo", 2], 
    ["userthree", 3], 
    ["userfour", 4], 
    captured_list_elm, 
    ["personTwo", 2], 
    ["personOne", 3], 
]; 

var status = mapping.indexOf(captured_list_elm); 
alert("status= "+status); 

什么你可能需要做的就是添加一个for循环,在你的阵列进行迭代,并比较值。

0

问题是,你正在比较两个阵列使用indexOf。如果你用这段代码运行你的jsFiddle,它将返回正确的索引,因为它比较了数组本身,而不是它内部的元素。

var status = mapping.indexOf(mapping[6]);