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

例子:

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

当前回答

= +_将_转换为一个数字。

So

var _ = "1",
   r = +_;
console.log(typeof r)

将输出数字。

其他回答

它不是赋值操作符。

_只是传递给函数的参数。 hexbin。半径=函数_ { // ^它被传递到这里 / /…… }; 下一行r = +_;+ infront将该变量(_)转换为一个数字或整数值,并将其赋给变量r

不要把它与+=运算符混淆

简单地说,+_相当于使用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.

r = +_;

+尝试将_转换为一个数字。 _只是一个变量名(不是一个操作符),它可以是a, foo等。

例子:

+"1"

将“1”转换为纯数字1。

var _ = "1";
var r = +_;

R现在是1,不是1。

此外,根据MDN的算术运算符页面:

一元加号运算符在其操作数之前,求值为its 操作数,但如果不是,则尝试将其转换为数字 了。[…它可以转换整数和的字符串表示 浮动,以及非字符串值true, false和null。 十进制和十六进制(“0x”前缀)格式的整数都是 支持。支持负数(但不支持十六进制)。如果它 不能解析一个特定的值,它将计算为NaN。

还注意到

一元加号是将数字转换为数字的最快和首选的方法

= +_将_转换为一个数字。

So

var _ = "1",
   r = +_;
console.log(typeof r)

将输出数字。

在这个表达式中:

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是可读性更好的选择。