将字符串转换为变量名称。 (JavaScript的) [英] Converting string to variable name. (JavaScript)

查看:104
本文介绍了将字符串转换为变量名称。 (JavaScript的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过以前的问题,但是它们是针对整数值的,我需要一个文本值的答案。



我之前问过一个与此相关的问题,这一周,但这里。
如下所示,Make [x]等于某个字符串值(Acura,Honda,Toyota)。当我将Make [x]传递给Models(Make)函数时,我怎样才能让这个字符串变成一个变量名,变量Acura,Honda和Toyota在Models(Make)函数中?

 函数模型(Make){
var Acura = ['RSX','NSX','Integra',];
var Honda = ['Accord','Civic','Prelude',];
var丰田= ['MR2','Celica','凯美瑞',];
var holder = Make;
var Model = holder [Math.floor(Math.random()* holder.length)];
return模型;


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

document.write(main());

如果运行,您将获得Make的名称,但不是模型而是吐出

你不能做什么你问什么你有目前的,但它会更有意义的创建模型的对象无论如何

 函数Models(Make){
var Models = {Acura:['RSX','NSX','Integra'] / * snip * /};
return模型[Make] [random()];
}


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()];
}

这篇关于将字符串转换为变量名称。 (JavaScript的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆