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);
}
CodePudding user response:
Just use a ternary condition that checks if x
is 5.
for (let x = 1; x < 11; x ) {
console.log(x (x == 5 ? ' text' : ''));
}
If you want the text before the number you can just move the expression like:
console.log((x == 5 ? 'text ' : '') x)
CodePudding user response:
for(let x = 0; x < 11; x ) {
console.log(x === 5 ? '5 with some text' : x);
}
if I understood your questioncorrectly, this should work
CodePudding user response:
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);
CodePudding user response:
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).
CodePudding user response:
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'))