Assuming that x is a positive integer, how would I return the first n multiples of the number x?
Here is what I have so far:
function multiples(x, n){
var arr=[];
for (var i=1; i<=x; ++i)
arr.push(n*i);
return arr;
}
console.log(
multiples(2, 5)
);
Assuming that x is a positive integer, how would I return the first n multiples of the number x?
Here is what I have so far:
function multiples(x, n){
var arr=[];
for (var i=1; i<=x; ++i)
arr.push(n*i);
return arr;
}
console.log(
multiples(2, 5)
);
What I want it to return is this: multiples(2, 5) // [2, 4, 6, 8, 10]
But what it actually returns is this: [5, 10]
-
3
You mistakenly swapped
x
andn
. What you want ismultiples(5, 2)
. – ASDFGerte Commented Dec 30, 2019 at 16:50 - 1 That's when you know it is time to take a break, thank you! – Cody Wirth Commented Dec 30, 2019 at 16:51
4 Answers
Reset to default 3You switched the x
and the n
in the for
loop
//changed var to const & let
function multiples(x, n) {
const arr = [];
for (let i = 1; i <= n; i++)
arr.push(x * i);
return arr;
}
console.log(multiples(2, 5));
Using ES6 spread operator you can do like this:
function multiples(x, n) {
return [...Array(n)].map((_, i) => x * ++i);
}
console.log(multiples(2, 5))
Using ES6 Array.from(...) you can do like this:
function multiples(x, n) {
return Array.from(Array(n)).map((_, i) => x * ++i);
}
console.log(multiples(2, 5))
x
swap n
function multiples(x, n){
var arr=[];
for (var i=1; i<=n; ++i)
arr.push(x*i);
return arr;
}
console.log(
multiples(2, 5)
);
You had the right idea, but swapped x
and n
in your loop:
for (var i = 1; i <= n; ++i)
arr.push(x * i);
const multiples = (x, n) => Array(n).fill().map((_, i) => x * ++i);
console.log(multiples(2, 5));
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744676105a4587336.html
评论列表(0条)