0

these are my arrays

var CarType=["RM","BM","GM"];
var CarName=["Red Mustang","Black Mustang","Green Mustang"]

how would I create a simple function that when a button is pushed an alert would pop up that displays something like this:

RM = Red Mustang

BM = Black Mustang

GM = Green Mustang

1
  • You could use a simple for loop to iterate over both arrays at once and concatenate the values to build up your message. Which part are you stuck on? (Also, I would store that data as a single array of objects: [{type:"RM", name: "Red Mustang"}, {type:"BM", name: "Black Mustang"}, ...].) Commented Apr 10, 2017 at 3:16

2 Answers 2

1

Here's a working solution. Hope it helps!

function myFunction() {
   var CarType=["RM","BM","GM"];
   var CarName=["Red Mustang","Black Mustang","Green Mustang"];
   var result = "";
   for(var i in CarType){
     result += [CarType[i] + " = " + CarName[i]] + "\n";
    }
   alert(result)
}
<button onclick="myFunction()">Click me</button>

Sign up to request clarification or add additional context in comments.

2 Comments

thanks so much this worked. Just so I can understand, what does the 'n' in "/n" do?
You're welcome!. The "\n" is just going to add a new line, that is all. Please mark my answer as the correct answer by clicking on the check mark and it will turn green. Thank you!
0

I haven't tested this, but it should go something like this.

Your arrays must have same size for this to work and sorted

function display(carType, carName) {

     var text = "";

     for (i=0; i < carType.length; i++) {
         text += carType[i] + " = " + carName[i] + "\n";
     }

     alert(text);
}

var CarType=["RM","BM","GM"];
var CarName=["Red Mustang","Black Mustang","Green Mustang"];

display(CarType, CarName);

Comments

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.