0

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.

1
  • I think you're going the wrong way about this. An object seems to be what you need. var cars = {acura: [], honda: [], ...}... Commented Feb 21, 2013 at 5:38

1 Answer 1

2

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()];
}
Sign up to request clarification or add additional context in comments.

4 Comments

I feared that, but why are you returning Make as an index to Models? Make is a string at this time, wouldn't you need an interger for indexing?
@GarrettMichaelGritzStelly not if it's an object. Only arrays need to be integer-indexed; objects can be string indexed (well, technically they have to be)
@GarrettMichaelGritzStelly be careful going down that road; the example I gave you is essentially just a simple string-based hash/dictionary (it's just that in JavaScript this data structure is called an "Object), but Objects in JS have a ton of other capabilities of varying complexity including use of the prototype and methods
Another thing to be aware of is that Object literals {} have no explicit order. If order matters you'll need an array [] as part of your solution.

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.