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
2 Answers 2
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>
answered Apr 10, 2017 at 3:31
Sign up to request clarification or add additional context in comments.
2 Comments
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
lang-js
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"}, ...]
.)