【问题标题】:what's the use of having plus sign infront of an expression在表达式前面加号有什么用
【发布时间】:2014-03-06 06:32:10
【问题描述】:
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
一般来说,我是编程新手,但是在表达式前面有一个 + 号的目的是什么,我在 jquery 库中看到了很多。
+(expression)
这些我能理解,因为它们是负面的:
-(1);// -1
【问题讨论】:
标签:
javascript
expression
operator-keyword
【解决方案1】:
它将字符串数字转换为表达式中的实际数字。
console.log(typeof +"1"); // number
console.log("1" + "1"); // 11
console.log(+"1" + +"1"); // 2
console.log("1.3" + "1.546"); // 1.31.546
console.log(+"1.3" + +"1.546"); // 2.846
引自ECMA 5.1 Standard Specifications for + operator,
一元+运算符将其操作数转换为数字类型。
在内部,JavaScript 字符串将根据 ECMA 5.1 标准中指定的these rules 转换为数字。
编辑:根据Number 规范,它还在内部使用相同的ToNumber 将其参数转换为数字。所以,从技术上讲,Number(<number string>) 与 +<number string> 相同。
【解决方案2】:
用于将值转换为浮点数。
+"123.25" + 2 = 125.25
类似
(x | 0)
它用于转换为整数(操作是按位或零)。
在 asm.js 中,这些形式也可以用作参数和局部变量的类型声明。