首页 > 解决方案 > 根据第二个值返回数组的第一个值

问题描述

我一直试图解决这个问题一段时间,但我一无所获。这是我到目前为止所拥有的:

var repeatNumbers = function(data) {
   var repeated = [];

   for ( var x = 0; x < data.length; x++){
     var unit = data[x][0]
     var quant = data[x][1]

     for(var i = quant; i > 0; i--){
       repeated.push(unit);
       repeated.join(',');
     }

     return repeated;
  }
};

console.log(repeatNumbers([1, 10]));

基本上我试图根据第二个值重复数组的第一个数字。任何见解将不胜感激,谢谢!:)

标签: javascript

解决方案


如果您只有两个数字,则不需要循环遍历数组,其中第一个数字(在索引 0 处)是您要重复的数字,第二个数字是您要重复该数字的次数(索引 1)。

一旦您有了希望重复该数字的次数,您就可以简单地使用for循环将该数字输入到您的repeated数组中该次数。

请参阅下面的工作示例(阅读代码注释以获得进一步解释):

var repeatNumbers = function(data) {
  var repeated = []
  
  var toRepeat = data[0]; // get the first number in the array
  var times = data[1]; // get the second number in the array
  
  // loop the number of times you want to repeat the number:
  for(var i = 0; i < times; i++) {
    repeated.push(toRepeat); // push the number you wish to repeat into the repeated array
  }
  
  return repeated.join(); // return the joined array (as a string - separated by commas)
}
console.log(repeatNumbers([1, 10]));


推荐阅读