将带有变量的字符串数组推入循环内的数组

时间:2019-01-21 16:09:34

标签: javascript arrays loops

有人可以帮我处理下面的代码吗?如何推送带有变量的数组?

function theBeatlesPlay(musicians, instruments) {
  var array = []
  var i;
  var m = ms[i];
  var it = its[i];
  var string = "`${m}` plays `${it}`";

  for (i = 0; i < 4; i++) {
    array.push(string)
  }

  return array
}

非常感谢!

3 个答案:

答案 0 :(得分:1)

您所做的大部分工作都应放在for循环中。像这样:

function theBeatlesPlay(musicians, instruments){
    var array = [];
    for(var i=0; i<musicians.length; i++){
        var m = musicians[i];
        var it = instruments[i];
        var string = `${m} plays ${it}`;
        array.push(string);
    }
    return array;
}

还要注意模板文字的语法:整个字符串由反引号分隔,并且您不应该使用双引号。

使用数组的实际长度代替迭代到4。

答案 1 :(得分:0)

function theBeatlesPlay(musicians, instruments){
    var array = []
    var i;
    for(i=0; i<4; i++){
        var m = ms[i];
        var it = its[i];
        var string = "`${m}` plays `${it}`";
        array.push(string)
    }
    return array
}

答案 2 :(得分:0)

是的,它是伪代码,实际上是这样;

var ms = ["a a", "b b", "c c"];
var its = ["d d", "e e", "f f"];
function funct(ms, its){
    var array = []
    var i =0;
    for(i=0; i<4; i++){
        var m = ms[i];
        var it = its[i];
        var string = "${m} plays ${it}";
        array.push(string)
    }
    return array
}