What is equivalent to PHP ". =" In Javascript to add something to a variable ..?

In PHP you can:

$myvar = "Hello"; $myvar .= " world!"; echo $myvar; 

Conclusion: Hello world!

How can I do this in javascript / jQuery ..?

+4
source share
6 answers
 var a = 'Hello'; a += ' world'; alert(a); 

A dialog with "Hello world" will appear.

Be careful with this:

 var a = 3; a += 'foo'; 

Result: 3foo . But:

 var a = 3; a += 4; a += 'b'; 

You will get an interesting result and probably not the one you expect.

+11
source

PHP concatenation operator .

Javascript concatenation operator is +

So you are looking for +=

+4
source

In JavaScript, the string concatenation operation is + , and the concatenation and assignment operator of a compound string is += . Thus:

 var myvar = "Hello"; myvar += " world!"; 
+2
source

Got it.

I did it:

 var myvar = "Hello"; var myvar += " world!"; var myvar += " again!"; 

I think a few var were my problem ...

Thanks to everyone.

+1
source

+ is a string concatenation operator in Javascript. PHP and Javascript, both of which are freely typed languages, deal with conflicts between adding and concatenation in different ways. PHP deals with it, having a completely separate statement (as you said . ). Javascript does this by having specific rules for which the operation is performed. For this reason, you need to know if your variable is being dialed as a string or number.

Example:

  • "1" + "3" : In PHP, this is equal to the number 4. In JavaScript, this is equal to "13". To get the desired 4 in Javascript, you would do Number("1") + Number("3") .

The main idea in Javascript is that any two variables that are typed as numbers with the + operator between them will be added. If either a string, it will be concatenated.

+1
source

var a = "Hello"; a + = "peace!";

Conclusion: Hello world!

0
source

Source: https://habr.com/ru/post/1311252/


All Articles