简体   繁体   English

什么相当于PHP的“。=”在Javascript中,为变量添加一些东西..?

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

In PHP you can do: 在PHP中,您可以:

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

The output is: Hello world! 输出是:Hello world!

How can I do this in Javascript/jQuery..? 我怎么能在Javascript / jQuery中做到这一点..?

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

You'll get a dialog with "Hello world". 您将看到一个“Hello world”对话框。

Be careful with this, though: 但是要小心,

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

Result: 3foo . 结果: 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 . PHP连接运算符是.

The Javascript concatenation operator is + Javascript连接运算符是+

So you're looking for += 所以你要找+=

In JavaScript the string concatenation operation is + and the compound string concatenation and assignment operator is += . 在JavaScript中,字符串连接操作为+ ,复合字符串连接和赋值运算符为+= 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. +是Javascript中的字符串连接运算符。 PHP and Javascript, both being loosely-typed languages, deal with conflicts between addition and concatentation in different ways. PHP和Javascript都是松散类型的语言,以不同的方式处理加法连接之间的冲突。 PHP deals with it by having a completely separate operator (as you stated, . ). PHP通过拥有一个完全独立的运算符来处理它(如你所说, . )。 Javascript deals with it by having certain rules for which operation is being performed. Javascript通过具有执行哪些操作的某些规则来处理它。 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". "1" + "3" :在PHP中,这等于数字4.在JavaScript中,这等于“13”。 To get the desired 4 in Javascript, you would do Number("1") + Number("3") . 要在Javascript中获得所需的4 ,您将执行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. Javascript中的基本思想是,将添加任何两个变量,它们都被键入为NUM,中间带有+运算符。 If either is a string, they will be concatenated. 如果其中一个是字符串,则它们将被连接。

var a="Hello"; var a =“你好”; a+="world !"; a + =“世界!”;

output: Hello world! 输出:Hello world!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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