1

I need to create a string like this: 01-2--3---4----5-----6------7------- for a let n=7, using a loop. I've created something like this so far:

let numbers = '';
n = 7;
for(i=0; i<=n; i++) {
numbers += i;
if (i>0) {
numbers += ('-')
}}

which gives me: "01-2-3-4-5-6-7-". Don't know how to change the code so that it could multiply the number of '-' equal n in every loop.

asked Nov 28, 2020 at 21:49

3 Answers 3

1

What you need is a nested loop, to iterate over the value of i in the outer loop.

const n = 7
let result=''
for (let i = 0; i <= n; i++) {
 let dashes=''
 for(let j=0; j < i; j++){
 dashes+='-'
 }
 result+= `${i}${dashes}`
}
console.log(result)

answered Nov 28, 2020 at 22:01
Sign up to request clarification or add additional context in comments.

Comments

0

You could use String#repeat for the wanted dash.

Do not forget to declare any variable.

let numbers = '',
 n = 7;
for (let i = 0; i <= n; i++) numbers += i + '-'.repeat(i);
console.log(numbers);

answered Nov 28, 2020 at 21:56

Comments

0

This the solution for your problem:

var numbers = '';
var n = 7;
for(var i = 0; i <= n; i++) {
numbers += i;
 for(var j = 0; j < i; j++) {
 numbers += "-";
 }
}
answered Nov 28, 2020 at 22:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.