1

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(""));
    }

1
  • Some alteratives here Commented Feb 12, 2020 at 16:31

4 Answers 4

1

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()

Sign up to request clarification or add additional context in comments.

Comments

1

[...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

2 Comments

Thank you so much for the detailed explanation. I will go have a look at String.prototype.padStart aswell.
@StefanVisser hm. i didn't think this through. just look for String.prototype.repeat since you can just do: "*".repeat(7)
0

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

1 Comment

Thank you for the link. I will go have a look.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.