0

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.

4
  • 1
    what do you mean by 'array name'? Commented Feb 20, 2015 at 21:31
  • I have few arrays. For example: eyes, clothes, hair. I want to specify "type" variable as one of those 3. Commented Feb 20, 2015 at 21:34
  • you should just pass it in. Commented Feb 20, 2015 at 21:35
  • 2
    Passing an array to getElementById would not make sense. Commented Feb 20, 2015 at 21:37

1 Answer 1

1

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){

    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

I guess that should be parts[type].indexOf(...).
@FelixKling: Yep. Completely missed they had that there.
So without arranging arrays into object it's not possible to easily convert string to array name which exists already? I have 7 arrays which share same function but accessing different array, I would love if I can re-use that function by just specifying which array to use in parameters.
@arleitiss: You can, by putting them in an object. And as a bonus you don't have 7 arrays polluting the global namespace, instead you have just one object. Technically, you could use eval, but don't. It's terrible practice.
@MattBurland I found another answer on stackoverflow last night, it suggested just writing: this[arrayname/paramter] and that works as reference to array I want (basically what I want to get done), not using eval

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.