简体   繁体   English

将字符串转换为变量名称。 (JavaScript的)

[英]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). 如下所示,我让Make [x]等于一些字符串值(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? 当我将Make [x]传递给函数Models(Make)时,如何在模型(Make)函数中为变量Acura,Honda和Toyota变为变量名?

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. 如果运行,您将获得Make的名称,但不是模型,而是从模型名称中吐出一个字母来代替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()];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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