[英]How to push multiples of a number to array?
How would one push multiples of a number to an array? 如何将数字的倍数推入数组? For example, if the input is (6), I want to create an array that holds
[6, 12, 18, 24, 30, 36, etc...]
例如,如果输入为(6),我想创建一个包含
[6, 12, 18, 24, 30, 36, etc...]
6、12、18、24、30、36等的数组[6, 12, 18, 24, 30, 36, etc...]
The most intuitive method to me does not work. 对我而言,最直观的方法无效。
for (var i = 0; i < 10; i++) {
firstArray.push(arr[0] *= 2);
}
This multiplies the number that comes before it by 2, causing an exponential growth. 这会将前面的数字乘以2,从而导致指数增长。 [14, 28, 56, 112, 224, 448, 896, 1792, etc.]
[14、28、56、112、224、448、896、1792等。]
How would one achieve this? 一个人将如何实现这一目标?
Problem: 问题:
The problem in the code, as commented by Pranav is the use of multiplication by two in the for
loop. 正如Pranav所评论的那样,代码中的问题是在
for
循环中使用了2的乘法。
Using i
iterator index can solve the problem. 使用
i
迭代器索引可以解决此问题。
firstArray.push(6 * (i + 1));
As i
is starting from 0
, i + 1
will give the number which is 1-based . 正如
i
是从开始0
, i + 1
将给出其基于1的数目。
Another Approach: 另一种方法:
First add the number 首先添加号码
var num = 6,
arr = [num];
Then add the number which is double of the previous in the array. 然后添加数字,该数字是数组中前一个数字的两倍。
for (var i = 1; i < 10; i++) {
arr.push(arr[i - 1] + num);
}
var arr = [6]; for (var i = 1; i < 10; i++) { arr.push(arr[i - 1] + arr[0]); } console.log(arr);
The same thing can also be done in single line using for
loop. 使用
for
循环也可以在单行中完成同一件事。
var arr = []; for (let i = 0, num = 6; i < 10; i++, num += 6) { arr.push(num); } console.log(arr);
You can use map
: 您可以使用
map
:
function multiplyArrayElement(num) {
return num * 2;
}
numbers = [6, 12, 18, 24, 30, 36];
newArray = numbers.map(multiplyArrayElement);
https://jsfiddle.net/25c4ff6y/ https://jsfiddle.net/25c4ff6y/
It's cleaner to use Array.from . 使用Array.from更干净。 Just beware of its browser support.
只是要注意其浏览器支持。
Array.from({length: 10},(v,i) => (i + 1) * 6)
try this one 试试这个
for (var i = 0; i < 10; i++) {
firstArray.push(arr[0] * (i+1));
}
var arr = [];
var x = 6; //Your desired input number
var z;
for(var i=1;i<10;i++){
z = (x*i);
arr.push(z);
}
console.log(arr);
"One line" solution with Array.fill
and Array.map
functions: 具有
Array.fill
和Array.map
函数的“单行”解决方案:
var num = 6;
var arr = new Array(10).fill(0).map(function(v, k){ return num *(k + 1); });
console.log(arr); // [6, 12, 18, 24, 30, 36, 42, 48, 54, 60]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.