Javascript 列表列表的Array.indexOf不工作
我在Javascript 列表列表的Array.indexOf不工作,javascript,indexof,Javascript,Indexof,我在ajax响应中有一个来自服务器的列表,其结构如下: var mapping = [ //response.mapping ["userOne", 1], ["userTwo", 2], ["userthree", 3], ["userfour", 4], ["personOne", 1], ["personTwo", 2], ["personOne", 3], ]; 因为列表将永远不变,在任何时候都只有7个元素。我想要它的任
ajax响应中有一个来自服务器的列表,其结构如下:
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不能计算其指数
- 找到它的方法是什么,只通过循环列表获取索引
创建一个
注意-实际上,它应该是一个json,但我们团队中有人将它写成了一个列表列表。我现在无法更新它,因为代码正在生产中。使用严格相等(==
)来查找元素。映射的元素是数组,恰好具有相同元素的两个不同数组不是=
。我怀疑process\u mapping\u list()
返回的数组看起来像mapping
的元素之一,但不是元素本身(就像您的小提琴一样)
您可能需要编写自己的查找函数,使用自定义的相等性测试。对于这样的测试,请查看。根据所针对的环境,您可能可以使用而不是indexOf()
。该函数允许您提供自己的测试函数。这里有一种方法可以解决indexOf
选项1:
- 创建一个包含字符串化数组的临时数组,然后比较字符串化值
- JSFiddle:
var-mapping=[//response.mapping
[“用户一号”,1],
[“用户二”,2],
[“用户三”,3],
[“用户四”,4],
[“personOne”,1],
[“personTwo”,2],
[“personOne”,3],
];
var jsonMapping=[];
对于(var i=0;i
选项2
- For循环比较
- JSFiddle:
var-mapping=[//response.mapping
[“用户一号”,1],
[“用户二”,2],
[“用户三”,3],
[“用户四”,4],
[“personOne”,1],
[“personTwo”,2],
[“personOne”,3],
];
var findIndex=函数(草堆、针){
对于(var i=0;i
为了确认@ted hopp给出的答案,我把你的JSFIDLE交给了他。基本上,我所做的是将变量captured\u list\u elm
移到顶部,并将其作为值添加到数组中。如您现在所见,Array.indexOf返回4,这是正确的(基于零的)索引:
您可能要做的是添加一个for循环,该循环在数组上进行迭代并比较值。问题是您正在使用indexOf比较两个数组。如果用这段代码运行JSFIDLE,它将返回正确的索引,因为它比较的是数组本身,而不是数组中的元素
var status = mapping.indexOf(mapping[6]);
演示:process\u mapping\u list.@sirrocco-让我添加一个JSFIDLE.@sirrocco-删除了该函数,我认为演示不需要它。看一看。@TedHopp-好的,非常感谢。完美地回答了我的期望。
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);
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);
var status = mapping.indexOf(mapping[6]);