[英]Use a variable for the index of an array in javascript
Here is my code: 这是我的代码:
var span = getSpanWithClass("galleria-current");
var slideNumber = span.innerHTML
var imageIDDivs = document.getElementsByClassName("slideshowImage");
var singleimageidDiv = imageIDDivs[slideNumber]
If I use this, sigleImageidDiv
doesn't have anything in it. 如果使用此功能,则
sigleImageidDiv
中没有任何内容。 If I just put 0 or 1 in like this: 如果我只是这样输入0或1:
var singleimageidDiv = imageIDDivs[1]
It works fine. 工作正常。
slideNumber
is 1
, in my test cases. 在我的测试案例中,
slideNumber
是1
。
I have tried these as well: 我也尝试过这些:
var singleimageidDiv = imageIDDivs[Number(slideNumber)]
var singleimageidDiv = imageIDDivs[parseInt(slideNumber)]
What is the proper way to use a variable as the index of an array? 使用变量作为数组索引的正确方法是什么?
innerHTML
returns the string inside the element, so if even if you have a number inside your element, it'll be returned as a string, that's why when you use that variable as an index for your array, you don't get a result. innerHTML
返回元素内的字符串,因此即使元素内有数字,它也将作为字符串返回,这就是为什么当使用该变量作为数组的索引时,不会得到结果的原因。 Using parseInt is an acceptable solution, you could also just do something like span.innerHTML * 1
, that would force JS to treat the string as an integer. 使用parseInt是可以接受的解决方案,您也可以执行
span.innerHTML * 1
,这将迫使JS将字符串视为整数。
我认为您的getSpanWithClass
函数有错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.