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]));
基本上我试图根据第二个值重复数组的第一个数字。任何见解将不胜感激,谢谢!:)
解决方案
如果您只有两个数字,则不需要循环遍历数组,其中第一个数字(在索引 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]));
推荐阅读
- java - 拆分方法和拆分上的'.' 字符(没有 csv 扩展名)
- c# - ASP.Net_SessionId cookie中SQL注入(延迟注入)的预防及原因
- javascript - 如果我不知道深度是多少,如何在 Javascript 中动态处理嵌套对象?
- excel - 找到一个标题,复制一个特定的范围,找到一个标记并将其粘贴到那里
- wxpython - 如何在 wx.GridBagSizer 中正确包含 wx.grid?
- sql - 按两个带日期的案例陈述分组
- python - 返回一个新字符串,其中第 x 个字符(从 0 开始)现在后跟 *?
- operating-system - 饥饿与车队效应
- vue.js - vue.api.init、vue.api.call是什么?
- ios - 如何使用 MFMailComposerViewController 从自定义 UITableViewCell 发送邮件