我想知道= +_操作符在JavaScript中是什么意思。它看起来像是在做作业。
例子:
hexbin.radius = function(_) {
if (!arguments.length)
return r;
r = +_;
dx = r * 2 * Math.sin(Math.PI / 3);
dy = r * 1.5;
return hexbin;
};
我想知道= +_操作符在JavaScript中是什么意思。它看起来像是在做作业。
例子:
hexbin.radius = function(_) {
if (!arguments.length)
return r;
r = +_;
dx = r * 2 * Math.sin(Math.PI / 3);
dy = r * 1.5;
return hexbin;
};
当前回答
_只是一个变量名,作为函数hexbin的参数传递。半径,并将其转换为数字
让我举一个和你的函数一样的例子。
var hexbin = {},r ;
hexbin.radius = function(_) {
if (!arguments.length)
return r;
console.log( _ , typeof _ )
r = +_;
console.log( r , typeof r , isNaN(r) );
}
并运行这个示例函数..的输出
hexbin.radius( "1");
1 string
1 number false
hexbin.radius( 1 );
1 number
1 number false
hexbin。半径([]);
[] object
0 number false
hexbin。半径('a');
a string
NaN number true
hexbin。半径({});
Object {} object
NaN number true
hexbin。半径(真);
true boolean
1 number false
其他回答
我想你的意思是r = +_;?在这种情况下,它将参数转换为数字。假设_是'12.3',那么+'12.3'返回12.3。所以在引用语句中+_被赋值给r。
+_几乎等同于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
简单地说,+_相当于使用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 = +_;
'+'在这里作为一元操作符,尝试转换右操作数的值。它不转换操作数,而是转换被求值。所以_仍然是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是可读性更好的选择。
= +_将_转换为一个数字。
So
var _ = "1",
r = +_;
console.log(typeof r)
将输出数字。