简体   繁体   English

在JavaScript中使用变量作为数组的索引

[英]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. 在我的测试案例中, slideNumber1

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? 使用变量作为数组索引的正确方法是什么?

Parse to int with a radix. 用基数解析为int。

This is the proper way of doing it: 这是正确的方法:

imageIDDivs[parseInt(slideNumber, 10)];

Live DEMO If it doesn't work, then your problem is somewhere else. 实时演示如果它不起作用,则您的问题出在其他地方。


BTW indexes work with strings as well. BTW索引也适用于字符串。 DEMO DEMO

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM