简体   繁体   English

如何在控制台中将文本添加到值,而不破坏它

[英]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.只需使用检查x是否为 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.您需要创建一个变量来存储所有 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).另一个想法是使用switch statement (对于很多情况“在 1 上做某事”、“2”和“5”等可能更具可读性)。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch 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; default可选 默认子句; if provided, this clause is executed if the value of expression doesn't match any of the case clauses.如果提供,则如果表达式的值不匹配任何 case 子句,则执行此子句。

** out of topic: it is more common to use i inside for loop ( i == index). ** 题外话:在for循环中使用i更为常见( i == 索引)。

If I understand you correctly, you want a string (in this case 5 ) to be added after each value.如果我理解正确,您希望在每个值之后添加一个字符串(在本例中为5 )。 If so, Array.prototype.map() will do that job for you.如果是这样, Array.prototype.map()将为您完成这项工作。

 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() .如果要为特定值定义5 ,可以使用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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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