arleitiss
arleitiss

Reputation: 1304

JavaScript: Convert String as Parameter to Array Name?

is it possible to convert Function Parameter string to Array name?

function SwitchElement(type){

    var cur = type.indexOf(document.getElementById(type).src);
    console.log(cur);
    if(cur < eyes.length-1){

    }
}

So that "type" is Addressed as array name.

If so, how? I am trying to do it just like that function but it returns me index -1

Note: Div of element and Arrayname share same name.

Upvotes: 0

Views: 1111

Answers (1)

Matt Burland
Matt Burland

Reputation: 45155

Assuming you are passing in a string, the best way to handle this would be to arrange your arrays into an object. So instead of:

var skins = [];
var eyes = [];
// etc...

You'll have something like:

parts = {
    skins: [],
    eyes: [],
    // etc
};

Now in your function you can do something like:

function SwitchElement(type){

    var cur = parts[type].indexOf(document.getElementById(type).src);
    console.log(cur);
    if(cur < parts[type].length-1){

    }
}

Upvotes: 1

Related Questions