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
What is the purpose of a plus symbol before a variable?
提问by goh
this really sounds like a simple question but I had no luck searching. what does the +d
in
这真的听起来像一个简单的问题,但我没有运气搜索。+d
in是什么意思
function addMonths(d, n, keepTime) {
if (+d) {
means?
方法?
回答by Paul Sonier
回答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 addMonths
function in the question):
示例(使用问题中的addMonths
函数):
addMonths(34,1,true);
addMonths("34",1,true);
then the +d
will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d
is a number, a function or a string that can be converted to a number.
那么+d
在所有情况下都将评估为一个数字。从而避免需要检查类型并根据d
是数字、函数还是可以转换为数字的字符串采用不同的代码路径。