首页 > javascript 中 +a 代表什么呢

javascript 中 +a 代表什么呢

例如,对于这个例子,我们给定一个直角三角形的两条边的长度,需要求第三条边的长度

function calculateHypotenuse(a,b){
  if (!+a || !+b || typeof(a) != 'number' || typeof(b) != 'number' || a<0 || b<0) 
    throw 'error';
  return Math.sqrt(a*a + b*b).toFixed(3);
}

在这个例子中 +a 代表什么呢?
经过测试 a 对于 string 类型,0 都满足 !+a;

var a = 1;
console.log(+a);    //1
console.log(a); //1
console.log(++a);   //2
console.log(a++);   //2
console.log(a++)    //3

而在这里,+a 好像并没有改变 a 的值。。


这里的+a,+b作用在于判断a,和b是否有参数传入,缺少参数之一,抛出异常。

此函数先判断是否a和b两个参数齐全,在判断两个参数是否是数字类型,然后判断是否都大于0,只有为a和b都为大于零的整数才参与最后的计算。

当a或b一个参数为定义的实收。!+a 或者 !+b 结果将为true,满足条件,抛出异常,这个作用和 typeof(a)=="undefined" 这样的语句是一样的。另外,当a或b传入的参数为 "15a" 这样的字符串的时候,表达式计算结果也为true,最终也将抛出异常。

//此时没定义a 
!+a //true
a='12c';
!+a //true

可以这么认为:+a 就是 正a;-a 就是 负a,所以这里显然会被转成数值类型,感受"鸭子"的魅力吧,骚年。


php+a是转为number类型,同parseInt(a)
var a = 1;
console.log(+a);    //parseInt(a)=1
console.log(a); //1
++a是先加1,然后返回a
a++是先返回a,然后加1

+a 会对试着对a做朝着数值类型的转换,这样对于'0'这样的值就和'1'不同了,比如

+'1' === 1
+'0' === 0

在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Oper... 中提到

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.


我觉得@socrates说的在一般情况下是对,但是不符合题意,如果为了转成number,后面的typeof就没必要存在了。我觉得@晴云孤魂 。说得比较合理

【热门文章】
【热门文章】