我想知道= +_操作符在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;
};
当前回答
不是=+。在JavaScript中,+表示将其更改为数字。
+'32'返回32。
+“a”南。
因此,您可以使用isNaN()来检查它是否可以更改为number。
其他回答
=+实际上是两个运算符=是赋值,+和_是变量名。
如:
i = + 5;
or
j = + i;
or
i = + _;
下面的代码将帮助您展示如何使用=+将字符串转换为int。 例子:
y = +'5'
x = y +5
alert(x);
输出10
这里y是int 5,因为=+ 否则:
y = '5'
x = y +5
alert(x);
输出55
其中as是一个变量。
_ = + '5'
x = _ + 5
alert(x)
输出10
此外, 有趣的是,你也可以用~(如果字符串是int字符串(float将是整轮到int))实现同样的事情。
y = ~~'5' // notice used two time ~
x = y + 5
alert(x);
也输出10
~是按位的NOT:将其操作数的位反转。我做了两次,幅度没有变化。
+_几乎等同于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
= +_将_转换为一个数字。
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是可读性更好的选择。
简单地说,+_相当于使用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.