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.
asked Feb 20, 2015 at 21:30
arleitiss
1,2961 gold badge14 silver badges38 bronze badges
1 Answer 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){
}
}
answered Feb 20, 2015 at 21:50
Matt Burland
45.3k18 gold badges110 silver badges182 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Felix Kling
I guess that should be
parts[type].indexOf(...).Matt Burland
@FelixKling: Yep. Completely missed they had that there.
arleitiss
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.
Matt Burland
@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.arleitiss
@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
lang-js
getElementByIdwould not make sense.