简体   繁体   中英

How to add text to value in console, without breaking it

so the code bellow would write ten numbers in the console. How could I add some text behind, lets say, number five? So it would write numbers like usual, but the number five would have also some text to it.

 for (let x = 1; x < 11; x++) { console.log(x); }

Just use a ternary condition that checks if x is 5.

 for (let x = 1; x < 11; x++) { console.log(x + (x == 5? ' text': '')); }

 for(let x = 0; x < 11; x++) { console.log(x === 5? '5 with some text': x); }

if I understood your questioncorrectly, this should work

You need to create a variable to store all of the output. For example you want it to be space-separated then.

let output = "";

for (let x = 1; x < 11; x++) {
 
  output += x + " ";

  if (x == 5) {
     output += "add something”;
  }

}
console.log(output);

One more idea is to use switch statement (Could be more readable for a lot of cases "do something on 1" and "2" and "5" and so on).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

 <script> for (let i = 1; i < 11; i++) { switch (i) { case 1: console.log("hello: " + i); break; case 5: console.log("hello: " + i); break; default: console.log(i); } } </script>

default Optional A default clause; if provided, this clause is executed if the value of expression doesn't match any of the case clauses.

** out of topic: it is more common to use i inside for loop ( i == index).

If I understand you correctly, you want a string (in this case 5 ) to be added after each value. If so, Array.prototype.map() will do that job for you.

 console.log([1,2,3,4,5,6,7,8,9,10].map(item => item + '5'))

If you want to define 5 for specific values, you can use Array.prototype.filter() .

See this example:

 // Select only odd numbers and then add the number 5 behind them console.log([1,2,3,4,5,6,7,8,9,10].filter(value => Math.abs(value % 2) === 1).map(item => item + '5'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM