根据第二个值返回数组的第一个值

时间:2018-12-31 02:31:44

标签: javascript

一段时间以来,我一直在试图解决这个问题,但我还是一片空白。这是我到目前为止的内容:

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

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

2 个答案:

答案 0 :(得分:0)

如果只有两个数字,则不需要遍历数组,其中第一个数字(索引为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]));

答案 1 :(得分:0)

如果我正确理解了您的问题,则您希望函数repeatNumbers()返回一个数组,其中数组中的第一个元素被传递的数组中的第二个元素复制。

要实现这一目标,您可以执行以下操作:

var repeatNumbers = function(data) {

  // Extract the "value" to be repeated, and the "repeated" value
  // that will control the number of "value" items in result array
  var value = data[0];
  var repeated = data[1];

  var result = []

  // Loop over repeated range, and push value into the result array
  for (var i = 0; i < repeated; i++) {
    result.push(value);
  }

  // Result result array
  return result;
};

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

或者,如果您不需要支持IE,则更简洁的方法是:

var repeatNumbers = function(data) {

  var value = data[0];
  var repeated = data[1];
  
  return (new Array(repeated).fill(value));
};

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

相关问题