[英]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.