简体   繁体   中英

How can I access an array using an objects name value?

What I am trying to do

I am trying to access several arrays by passing a parameter to a function that is basically controls a slideshow. The parameter I pass to the function is the name of a <a href=#" name="rebounding" onclick="nextPlayer(this.name)"></a> . Here is one of the arrays I am trying to access. var reboundingImgs = ['tyson_chandler.png', 'dwight_howard.png', 'zach_randolph.png', 'omer_asik.png', 'nikola_vucevic.png', 'joakim_noah.png'];

The problem

When I pass the parameter to the function that changes the image and I use the [index] instead of getting the index in the array called reboundingImgs[] I get the letter in the string parameter . eg parameter + "Imgs"[index] would be "b" if index was 2 and the parameter I pass in is "rebounding". I need to access the arrays using the parameter I pass in to show the right image from the right array( I have several arrays containing images eg scoringImgs[], reboundingImgs[], assistsImgs[], etc)

Here is my code

function nextPlayer(typeStatStr) {
    var numImgs = 6;
    var img = document.getElementById("slideImage");
    var imageName = img.name.split("_"); 
    var index = imageName[1];
    if (index == numImgs -1) {
        return;
    } 
    else {
        index++;
    }
    img.src = "..\\nbaart\\" + typeStatStr + "Imgs"[index];
    img.name = "image_" + index;
}

function prevPlayer(typeStatStr) {
    var img = document.getElementById("slideImage");
    var imageName = img.name.split("_");
    var index = imageName[1];
    if (index == 0) {
        return;
    }
    else {
            index--;
    }
    img.src = "..\\nbaart\\" + typeStatStr + "Imgs"[index];
    img.name = "image_" + index;
}

Why don't pass the proper array as a parameter to the function?

nextPlayer(reboundingImgs);

And then just:

typeStatStr[index];

Anyway, if the arrays are some sort of global variables (window scope?) then you can do this:

window[typeStatStr + "Imgs"][index];

Make an object which has properties that you can access given the name of the arrays:

var imgs = {};

imgs.rebounding = ['tyson_chandler.png', 'dwight_howard.png', 
                   'zach_randolph.png', 'omer_asik.png', 
                   'nikola_vucevic.png', 'joakim_noah.png'];

alert(imgs["rebounding"][0]); // tyson_chandler.png

String is just type character array so by doing: "Imgs"[index]; you are accessing the index-th element of the array of "Imgs". For instance "Imgs"[2] == 'g' .

If you want to access the index-th element of the array Imgs then you should do:

Imgs[index]; //Without the quotes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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