0
While loop question about +=
PLEASE HELP +++ can someone explain me the following code : while (i < 10) { text += "The number is " + i; i++; } Why is there used the "+=" symbol? Doesn't it mean, that you add text with text? What sense does it have? It's a code from W3schools. I just don't get that :(
8 ответов
+ 2
+= is a composite assignment operator that updates the existing value of variable on the left hand side by adding (appending in your case) rhs value to it.
Above code will result into
text += "This number is " + I will give
This number is 1This number is 2This number is 3....This number is 9
+ 9
in JS + is used (among other things) for concatenating strings.
'a'+'b'='ab', but be careful with that. JS reacts a bit strange sometimes due to the fact that it is an interpretive non-type-strict scripting language which tries to get some result out of anything.
+ 2
Let's simply the statement
text += "The number is " + i
text = text + "The number is " + 1
"The number is " + 1 work from left to right
and since its string before + operator, it will concatenate the operand after + operator (auto casting into string)
To get arithmetic sum, change code as follows
text=0
while (i < 10) {
text += i;
i++;
}
+ 2
You got it man😉
0
But why is it updated with the code on the right? I thought something would be ADDED. For example it it would be *= the variable on the left side will be multiplied with the variable on the right side. So it should have be 1+3 or am I wrong? I don't get that..
0
Ok cold on. So if we get back to the code above at the beginning this would mean =
Text = text + text, right?
Thus : "the number is" + i + "the number is" + i
You know what I am trying to say? So is it ADDED or REPLACED? :-) it's a little bit confusing..
0
Perfect dude!!! :-)
0
don't department on sololearn. you must learn
basics first. see YouTube video like durasoft channel.