Combining two arrays with for loops

user7944307
var number = [1,2,3,4];
var assignment= ["first", "second", "third", "fourth"];

I need to combine these two arrays so that it console logs this information like so:

1 first
2 second
3 third
4 fourth

Thank you.

lu5er

You can combine them like

var number = [1,2,3,4]; var assignment= ["first", "second", "third", "fourth"];
// alert (number[i] + " = " + assignment[number[i]-1]);
// change "i" as desired
alert (number[0] + " = " + assignment[number[0]-1]);

Now you can loop and combine them like this,

var number = [1,2,3,4]; var assignment= ["first", "second", "third", "fourth"];
for(var i=0;i<4;i++)
{
  alert (number[i] + " = " + assignment[number[i]-1]);
}

I you want a string, you can do something like this,

var number = [1,2,3,4]; var assignment= ["first", "second", "third", "fourth"];
var txt = "";
for(var i=0;i<4;i++)
{
  txt = txt + (number[i] + " = " + assignment[number[i]-1] + " ");
}
alert(txt);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related