MKN-97
MKN-97

Reputation: 1

Removing the space in the loop javascript

It is a counter function for descending number. I throw any number and it start to countdown to zero and I add space between them but the Problem is the last space! How can I remove it??

function countDown(number) {
  var s = "";
  for (let i = number; i >= 0; i--) {
    s += i + " ";
  }
  console.log("{" + s + "}"); // I add the brackets to show the last space  
}
    
countDown(10)


// result is : {10 9 8 7 6 5 4 3 2 1 0 }

Upvotes: 0

Views: 85

Answers (3)

gog
gog

Reputation: 11347

With "low-level" Javascript, without builtins, the trick is to add a delimiter before an item, not after it:

function countDown(number) {
   let s = String(number)
   for (let i = number - 1; i >= 0; i--)
      s += ' ' + i
   return s
}

console.log(JSON.stringify(countDown(10)))

If builtins are allowed, you don't even need a loop to produce this result:

result = [...new Array(11).keys()].reverse().join(' ')
console.log(result)

Upvotes: 0

Maximilian Ballard
Maximilian Ballard

Reputation: 996

This is a common pattern that one has to deal with in loops.

Typically you solve this by having a special case in the beggining or end of a loop. In this example it is easy just to have one in the beggining:

function countDown(number) {
  var s = number;
  for (let i = number - 1; i >= 0; i--) {
    s += " " + i;
  }
  console.log("{" + s + "}"); // I add the brackets to show the last space  
}
    
countDown(10)


// result is : {10 9 8 7 6 5 4 3 2 1 0}

Just assign s to the number in the beggining and decrease the starting number by 1.

Upvotes: 1

Christian Fritz
Christian Fritz

Reputation: 21364

This is a great use case for the Array.join function.

function countDown(number) {
  const list = [];
  for (let i = number; i >= 0; i--) {
    list.push(i);
  }
  console.log("{" + list.join(' ') + "}"); 
}
    
countDown(10)


// result is : {10 9 8 7 6 5 4 3 2 1 0}

Upvotes: 3

Related Questions