简体   繁体   中英

Converting string to variable name. (JavaScript)

I did look at the previous questions, but they are for integer values and I need an answer for text values.

I asked a question relevant to this earlier in the week, but here goes. As seen below, I have Make[x] equal to some string value (Acura, Honda, Toyota). When I pass that Make[x] into the function Models(Make), how can I get that string to become a variable name, for the variables Acura, Honda and Toyota within the Models(Make) function?

function Models(Make){
var Acura=['RSX','NSX','Integra',];
var Honda=['Accord','Civic','Prelude',];
var Toyota=['MR2','Celica','Camry',];
var holder = Make;
var Model = holder[Math.floor(Math.random()*holder.length)];
return Model;
}

function main(){
var Makes=['Acura','Honda','Toyota',];
var Make = Makes[Math.floor(Math.random() * Makes.length)];
var Model = Models(Make);
var Out = Make + " " + Model;
return Out;
}

document.write(main());

If run, you will get the name of the Make, but instead of a model it spits out a letter from the name of the Model in place of the make.

You can't do what you're asking with what you have currently, but it would make more sense to create an object of the models anyway

function Models(Make) {
    var Models = {"Acura": ['RSX','NSX','Integra'] /* snip */};
    return Models[Make][random()];
}

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