In PHP you can do:
$myvar = "Hello";
$myvar .= " world!";
echo $myvar;
The outp开发者_运维问答ut 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 desired4
in Javascript, you would doNumber("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!
精彩评论