我有一个名为 dataid 的数组,这是我的数组的 console.log
:
我想做到这一点,如果我单击 id 为“next”的范围,它会在我的 URL 中向我发送数组 datatid 中下一个 id 的值。因此,首先我们需要确定 myid 在数组中的位置,然后确定下一个要在 URL 中发送的值。
这是我尝试过的:
var newid = GetURLParameter('myid');
console.log(newid);
var dataid = localStorage.getItem("mesid");
console.log(dataid);
function nextticket(){
var position = dataid.indexOf(newid)+1;
console.log(dataid.indexOf(newid));
console.log(position);
}
但是位置错了!
最佳答案
localStorage 存储字符串,而不是数组。 输出中的位置 10 是因为“4653”出现在字符串“5475,4831,4653,...”中的字符位置 10 处。
您需要将字符串拆分回数组,如下所示:
var position = dataid.split(',').indexOf(newid) + 1;
此处使用的 split()
方法将逗号分隔的字符串转换为数组。
关于javascript - 比较值并确定数组中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36422471/