javascript: plus symbol before variable

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

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

means?


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 d is a non-zero number.

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


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


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

Example (using the addMonths function in the question):

addMonths(function(){return x*y;}, 1, true);
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.

链接地址: http://www.djcxy.com/p/73936.html

上一篇: 这个符号在JavaScript中意味着什么?

下一篇: javascript:在变量前加上符号