简体   繁体   English

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

[英]pushing array of string with variables to an array inside a loop

Could someone help me on below code?有人可以帮我处理下面的代码吗? How do I push an array with variables?如何推送带有变量的数组?

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
}

Thanks a lot in advance!非常感谢!

Most of what you did should be placed inside the for loop.你所做的大部分事情都应该放在for循环中。 Like this:像这样:

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;
}

Also note the syntax for the template literal: the whole string is delimited by backticks, and you should not have those double quotes.还要注意模板文字的语法:整个字符串由反引号分隔,您不应该使用那些双引号。

Instead of iteration to 4, use the actual length of the array.使用数组的实际长度而不是迭代到 4。

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
}

yes It is pseudo-code and It's actually something like this;是的,它是伪代码,实际上是这样的;

 var ms = ["aa", "bb", "cc"]; var its = ["dd", "ee", "ff"]; 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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM