我想知道= +_操作符在JavaScript中是什么意思。它看起来像是在做作业。

例子:

hexbin.radius = function(_) {
   if (!arguments.length)
       return r;
   r = +_;
   dx = r * 2 * Math.sin(Math.PI / 3);
   dy = r * 1.5;
   return hexbin;
};

当前回答

+_几乎等同于parseFloat(_)。注意,parseInt将停止在非数字字符,如点,而parshFloat不会。

经验值:

    parseFloat(2.4) = 2.4 
vs 
    parseInt(2.4) = 2 
vs 
    +"2.4" = 2.4

经验值:

var _ = "3";
    _ = +_;

console.log(_); // will show an integer 3

差别很小:

空字符串""的值为0,而parseInt()的值为NaN 更多信息请看这里:parseInt vs unary + -何时使用which

其他回答

在这个表达式中:

r = +_;

'+'在这里作为一元操作符,尝试转换右操作数的值。它不转换操作数,而是转换被求值。所以_仍然是1如果它原来是那么r将变成纯数。

考虑这些情况,是否要将+应用于数字转换

+"-0" // 0, not -0
+"1" //1
+"-1" // -1
+"" // 0, in JS "" is converted to 0
+null // 0, in JS null is converted to 0
+undefined // NaN
+"yack!" // NaN
+"NaN" //NaN
+"3.14" // 3.14

var _ = "1"; +_;_ // "1"
var _ = "1"; +_;!!_ //true
var _ = "0"; +_;!!_ //true
var _ = null; +_;!!_ //false

虽然,它是最快的数字转换器,我几乎不建议过度使用它,如果使用的话。parseInt/parseFloat是可读性更好的选择。

我想你的意思是r = +_;?在这种情况下,它将参数转换为数字。假设_是'12.3',那么+'12.3'返回12.3。所以在引用语句中+_被赋值给r。

它将给左边变量一个数字赋新值。

var a=10;
var b="asg";
var c=+a;//return 10
var d=-a;//return -10
var f="10";

var e=+b;
var g=-f;

console.log(e);//NAN
console.log(g);//-10

这是一个鬼鬼祟祟的问题。

需要理解的重要一点是,这里的下划线字符实际上是一个变量名,而不是一个操作符。

它前面的加号是得到下划线的正数值——即有效地将下划线变量转换为int型。您可以使用parseInt()实现相同的效果,但这里可能使用加号强制转换,因为它更简洁。

等号只是一个标准的变量赋值。

它可能不是故意写来混淆视听的,因为有经验的Javascript程序员通常会将下划线识别为变量。但如果你不知道,那肯定会很困惑。我当然不会这样写;在最好的情况下,我不喜欢使用没有意义的短变量名——如果你想在JS代码中使用短变量名来节省空间,请使用minifier;不要一开始就写短变量。

简单地说,+_相当于使用Number()构造函数。

事实上,它甚至适用于约会:

var d = new Date('03/27/2014');
console.log(Number(d)) // returns 1395903600000
console.log(+d) // returns 1395903600000

演示: http://jsfiddle.net/dirtyd77/GCLjd/


更多信息也可以在MDN - Unary plus(+)部分找到:

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.