jQuery javascript 中的减等于 - 这是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15664696/
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-26 15:32:38  来源:igfitidea点击:

minus equals in javascript - What does it mean?

javascriptjqueryoperators

提问by David Van Staden

What does the minus equals below -=mean/do?

下面的减等于什么-=意思/做什么?

$('#wrapper').animate({
    backgroundPosition: '-=2px'
})();

Thank you

谢谢

回答by George Reith

Adil has answered this but I always think it is useful to visualise problems and relate them to others.

Adil 已经回答了这个问题,但我始终认为将问题可视化并将其与其他人联系起来很有用。

The following two pieces of code have the same effect:

下面两段代码的效果是一样的:

var a = 20;
a = a - 5;

and

var a = 20;
a -= 5;

In both cases anow equals 15.

在这两种情况下,a现在都等于 15。

This is an assignment operator, what this means is that it applies whatever is on the right side of the operator to the variable on the left. See the following table for a list of assignment operators and their function:

这是一个赋值运算符,这意味着它将运算符右侧的任何内容应用于左侧的变量。有关赋值运算符及其功能的列表,请参阅下表:

Operator |  Example |  Same as    |  Result
______________________________________________
  =      |  a = 20  |             |  a = 20
  +=     |  a += 5  |  a = a + 5  |  a = 25
  -=     |  a -= 5  |  a = a - 5  |  a = 15
  *=     |  a *= 5  |  a = a * 5  |  a = 100
  /=     |  a /= 5  |  a = a / 5  |  a = 4
  %=     |  a %= 5  |  a = a % 5  |  a = 0

You also have the increment and decrement operators:

您还有递增和递减运算符:

++and --where ++aand --aequals 21 and 19 respectively. You will often find these used to iterate for loops.

++--其中++a--a分别等于21和19。您经常会发现这些用于迭代for loops

Depending on the order you will do different things.

根据顺序,您将做不同的事情。

Used with postfix(a++) notation it returns the number first then increments the variable:

后缀( a++) 表示法一起使用它首先返回数字然后增加变量:

var a = 20;
console.log(a++); // 20
console.log(a); // 21

Used with prefix(++a) it increments the variable then returns it.

前缀( ++a) 一起使用它增加变量然后返回它。

var a = 20;
console.log(++a); // 21
console.log(a); // 21

回答by Adil

The operator -=(Subtraction assignment) will subtract the given value from the already set valueof a variable.

运算符-=减法赋值)将从已设置value的变量中减去给定值。

For example:

例如:

var a = 2;
a -= 1;
//a is equal to 1