Javascript 变量前加号的用途是什么?

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

What is the purpose of a plus symbol before a variable?

javascript

提问by goh

this really sounds like a simple question but I had no luck searching. what does the +din

这真的听起来像一个简单的问题,但我没有运气搜索。+din是什么意思

function addMonths(d, n, keepTime) { 
    if (+d) {

means?

方法?

回答by Paul Sonier

The +operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not dis a non-zero number.

+运算符返回对象的数字表示。因此,在您的特定情况下,它似乎是在预测是否d为非零数字的 if 。

Reference here. And, as pointed out in comments, here.

参考这里。而且,正如评论中所指出的,这里.

回答by naivists

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

它是一个一元“+”运算符,它产生一个数字表达式。d*1我相信,这将与 相同。

回答by RubenLaguna

As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string functionthat evaluates to a number.

如其他答案中所述,它将变量转换为数字。当 d 可以是数字或字符串时特别有用功能计算结果为一个数字。

Example (using the addMonthsfunction in the question):

示例(使用问题中的addMonths函数):

addMonths(34,1,true);
addMonths("34",1,true);

then the +dwill evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether dis a number, a function or a string that can be converted to a number.

那么+d在所有情况下都将评估为一个数字。从而避免需要检查类型并根据d是数字、函数还是可以转换为数字的字符串采用不同的代码路径。