# = + _在JavaScript中是什么意思

2020/10/09 20:01 · javascript ·  · 0评论

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

``````r = +_;
``````
• `+`尝试将任何内容强制`_`转换为数字。
• `_`只是一个变量名（不是运算符），可以是`a``foo`等等。

``````+"1"
``````

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

`r`现在`1`，不是`"1"`

• `_` 只是传递给函数的参数。

``````hexbin.radius = function(_) {
//       ^ It is passed here
// ...
};
``````
• 在下一行，`r = +_;` `+`infront将变量（`_`强制转换为数字或整数值并将其分配给变量`r`

`=+`实际上是两个运算符`=`是赋值，`+`并且 `_`是变量名。

``````i = + 5;
or
j = + i;
or
i = + _;
``````

``````y = +'5'
x = y +5
``````

``````y = '5'
x = y +5
``````

``````_ = + '5'
x = _ + 5
``````

`~`（如果string是int string （float将舍入为int）实现相同的功能

``````y = ~~'5'  // notice used two time ~
x = y  + 5
``````

`~`是按位NOT：反转其操作数的位。我做了两次，幅度没有变化。

`+'32'` 返回32。

`+'a'` 返回NaN。

= + _将_强制转换为数字。

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

`_`只是一个变量名，作为function的参数传递`hexbin.radius`，并将`+`其转换为数字

``````var hexbin = {},r  ;

hexbin.radius = function(_) {
if (!arguments.length)
return r;
console.log( _ , typeof _ )
r = +_;
console.log( r , typeof r , isNaN(r) );
}
``````

``````1 string
1 number false
``````

``````1 number
1 number false
``````

``````[] object
0 number false
``````

``````a string
NaN number true
``````

``````Object {} object
NaN number true
``````

``````true boolean
1 number false
``````

``````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 d = new Date('03/27/2014');
console.log(Number(d)) // returns 1395903600000
console.log(+d) // returns 1395903600000
``````

`+_`几乎是等同`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
``````

• 空字符串的`""`值为a `0`，而parseInt（）的值为`NaN`
• 有关更多信息，请参见：parseInt与一元加-何时使用

``````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
``````