简体   繁体   中英

What's the equivalent of PHP's “ .= ” in Javascript, to add something to a variable..?

In PHP you can do:

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

The output is: Hello world!

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

var a = 'Hello';
    a += ' world';
alert(a);

You'll get a dialog with "Hello world".

Be careful with this, though:

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

Result: 3foo . But:

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

You'll get an interesting result, and probably not the one you expect.

The PHP concatenation operator is .

The Javascript concatenation operator is +

So you're looking for +=

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

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

Got it.

I was doing this:

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

I guess the multiple var was my problem...

Thanks all.

+ is the String concatenation operator in Javascript. PHP and Javascript, both being loosely-typed languages, deal with conflicts between addition and concatentation in different ways. PHP deals with it by having a completely separate operator (as you stated, . ). Javascript deals with it by having certain rules for which operation is being performed. For that reason, you need to be aware of whether your variable is typed as a String or a Number.

Example:

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

The basic idea in Javascript is that any two variables that are both typed as Numbers with a + operator in between will be added. If either is a string, they will be concatenated.

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

output: Hello world!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM