gpt4 book ai didi

javascript - 在数组中搜索字符串 - 返回 -1

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:32:35 24 4
gpt4 key购买 nike

我一直在阅读大量 StackOverflow 答案,这些答案告诉我,在 Javascript 中,搜索数组中特定字符串的最佳方法是使用 indexOf()。一段时间以来,我一直在努力使这项工作发挥作用,我需要一些帮助。

我正在文字冒险游戏中开一家商店。这些是我使用的值:

数组 shopCosts:

shopCosts = [20, 25];

数组 shopItems:

shopItems = [["Sword", "Shield"]];

我通过 shopItems循环动态创建单选按钮:

for(var i = 0; i < array.length; i++)
{
// Create the list item:
var item = document.createElement('li');

// Set its contents:
item.appendChild(document.createTextNode(array[i] + " - " + shopCosts[i] + " Gold"));

// Add it to the list:
list.appendChild(item);

var label = document.createElement("label");
var radio = document.createElement("input");
var text = document.createTextNode(array[i]);
radio.type = "radio";
radio.name = "shop";
radio.value = array[i];
radio.onclick = function () { addValue(this.getAttribute("value"), shopCosts, shopItems) }

label.appendChild(radio);
label.appendChild(text);
document.body.appendChild(label);
}

这是有问题的部分:

radio.onclick = function () { addValue(this.getAttribute("value"), shopCosts, shopItems) }

我的逻辑基本上是为每个动态创建的单选按钮分配值,如果按下一个单选按钮,则获取该值(因此,您要购买的商品的名称),然后在 shopItems 中搜索索引值的特定字符串。一旦我有了它,我就会在相同的“parallel”列表 shopCosts 中查找价格。

我使用 console.log() 来查看哪些变量在起作用。当我点击单选按钮时,这个函数被调用:

function addValue(nameOfItem, shopCosts, shopItems)
{
var positionOfShopItem = shopItems.indexOf(nameOfItem);
console.log(positionOfShopItem);
console..log(nameOfItem);
console.log(shopItems);
}

当然,console.log() 会返回指定项目的位置?为了向自己证明我没有发疯,开发工具是这样说的:

-1
Sword
[Array[2]]
0: "Sword"
1: "Shield"

Sword 显然在数组中,位置为 0,那么为什么 indexOf() 返回 -1

感谢任何帮助!

最佳答案

正如我在评论中提到的,这是因为 shopItems 不包含字符串数组,它包含一个元素,其中一个元素是一个字符串数组。我怀疑如果您删除多余的方括号,您的代码会正常工作

var shopItems = ["Sword", "Shield"];

关于javascript - 在数组中搜索字符串 - 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31297345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com