[英]How to add text to value in console, without breaking it
所以下面的代码会在控制台中写入十个数字。 我怎么能在后面添加一些文字,比如说,第五? 所以它会像往常一样写数字,但数字五也会有一些文字。
for (let x = 1; x < 11; x++) { console.log(x); }
只需使用检查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); }
如果我正确理解了您的问题,这应该可以
您需要创建一个变量来存储所有 output。 例如,您希望它是空格分隔的。
let output = "";
for (let x = 1; x < 11; x++) {
output += x + " ";
if (x == 5) {
output += "add something”;
}
}
console.log(output);
另一个想法是使用switch statement
(对于很多情况“在 1 上做某事”、“2”和“5”等可能更具可读性)。
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
可选 默认子句; 如果提供,则如果表达式的值不匹配任何 case 子句,则执行此子句。
** 题外话:在for
循环中使用i
更为常见( i
== 索引)。
如果我理解正确,您希望在每个值之后添加一个字符串(在本例中为5
)。 如果是这样, Array.prototype.map()将为您完成这项工作。
console.log([1,2,3,4,5,6,7,8,9,10].map(item => item + '5'))
如果要为特定值定义5
,可以使用Array.prototype.filter() 。
看这个例子:
// 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.