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

例子:

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

当前回答

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

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

其他回答

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

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

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

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

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.