Reputation: 19
So I am fairly new to JavaScript. I have a problem I need to solve. I came this far but don't know how to go further. I need to take the code below and execute the same result without using the for-loop.
for(var i = 0; i < 7; i++)
{
console.log([...Array(i)].map(x => '*').join(""));
}
Upvotes: 1
Views: 79
Reputation: 4947
[...Array(7)] // this will create a low performance array with seven entries
.map ( // both map and forEach provide three arguments: (value, index, array)
// in this case we care about the index to know where in the loop we are.
(x, i) => "*".repeat(i) // look up String.prototype.repeat.
)
.forEach(x => console.log(x)) // then for each iteration, call console.log
Upvotes: 1
Reputation: 676
Recursively call it to perform the same,
function drawStar(times) {
function drawRecursive(i) {
if (i === times) return;
console.log(Array(i).fill("*").join(""));
drawRecursive(++i);
}
drawRecursive(1);
}
drawStar(7);
Upvotes: 0
Reputation: 1099
I propose to use the same logic that you are using already. .map
argument function has index
parameter.
console.log([...Array(7)].map((x,i) => [...Array(i)].map(x => "*").join("")).join("\r\n"))
In the situations when you are not authorized to use loops you have recursive function option and Array.forEach()
Upvotes: 1
Reputation: 1
I recommend reviewing the documentation on arrays. To accomplish this without using a for loop, you could utilize the Array.forEach() method.
See MDN documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Upvotes: 0