将两个数组与for循环组合在一起

时间:2017-05-14 04:49:58

标签: javascript arrays variables numbers

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

我需要组合这两个数组,以便控制台记录这些信息,如下所示:

1 first
2 second
3 third
4 fourth

谢谢。

4 个答案:

答案 0 :(得分:1)

您可以将它们组合起来,如



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




现在你可以像这样循环和组合它们,



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]);
}
&#13;
&#13;
&#13;

我想要一个字符串,你可以做这样的事情,

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果阵列具有相同的亮度,则应该完成工作

git@github.com:USERNAME/OTHERREPOSITORY.git

然后你可以打印它们

答案 2 :(得分:0)

只要数组大小相同,以下内容就会起作用:

&#13;
&#13;
var number = [1,2,3,4];
var assignment = ["one","two","three","four"];
var size = number.count;
for(var i=0; i<size; i++){
    var log = number[i] + " " + assignment[i];
    console.log(log);
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

尝试forEach

var arr = [];
var number = [1, 2, 3, 4];
var assignment = ["first", "second", "third", "fourth"];
var i = 0;
number.forEach(function(e) {
  arr.push(e + ' ' + assignment[i++])
});
console.info(arr)

  

警告:我们假设数组大小相等