Javascript 中的 += 是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32957729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:25:31  来源:igfitidea点击:

What is += in Javascript?

javascriptloopswhile-loop

提问by HappyHands31

For example, in the while loop:

例如,在while循环中:

while (i < 10) {
    text += "The number is " + i;
    i++;
}

What does it do? Thanks.

它有什么作用?谢谢。

回答by Felipe Oriani

It is the addition assignmentoperator (+=) to add a value to a variable.

它是addition assignment操作者(+=)到一个值添加到一个变量。

Depending of the current type of the defined value on a variable, it will read the current value add/concat another value into it and define on the same variable.

根据变量上定义值的当前类型,它将读取当前值添加/连接另一个值并在同一变量上定义。

For a string, you concat the current value with another value

对于 a string,您将当前值与另一个值连接起来

let name = "User";

name += "Name"; // name = "UserName";
name += " is ok"; // name = "UserName is ok";

It is the same:

这是相同的:

var name = "User";

name = name + "Name"; // name = "UserName";
name = name + " is ok"; // name = "UserName is ok";

For numbers, it will sum the value:

对于数字,它将对值求和:

let n = 3;

n += 2; // n = 5
n += 3; // n = 8

In Javascript, we also have the following expressions:

在 Javascript 中,我们还有以下表达式:

  • -=- Subtraction assignment;

  • /=- Division assignment;

  • *=- Multiplication assignment;

  • %=- Modulus (Division Remainder) assignment.

  • -=- 减法赋值;

  • /=- 部门分配;

  • *=- 乘法赋值;

  • %=- 模数(除法余数)分配。

回答by slomek

text += "The number is " + i;

is equivalent to

相当于

text = text + "The number is " + i;