简体   繁体   English

J =“i = + i”是什么意思?

[英]What does “i = +i” mean in Javascript?

In jquery source: 在jquery源码中:

eq: function( i ) {
    i = +i;
    return i === -1 ?
        this.slice( i ) :
        this.slice( i, i + 1 );
},

Is it used for make sure parse i to int? 是否用于确保解析i到int?

Is it used for make sure parse i to int? 是否用于确保解析i到int?

No, it is to make sure that i is a number (either float or int ). 不,这是为了确保i是一个数字floatint )。 Given what the function is doing, it was better to convert i to an non-decimal value though, I'm not sure how slice handles decimals. 鉴于函数正在做什么,最好将i转换为非十进制值,但我不确定slice如何处理小数。

More information: MDN - Arithmetic Operators 更多信息: MDN - Arithmetic Operators

Almost, but any number is fine. 差不多,但任何数字都可以。

[ECMA-262: 11.4.6]: The unary + operator converts its operand to Number type. [ECMA-262: 11.4.6]:一元+运算符将其操作数转换为Number类型。

The production UnaryExpression : + UnaryExpression is evaluated as follows: 生产UnaryExpression:+ UnaryExpression的计算方法如下:

  1. Let expr be the result of evaluating UnaryExpression. expr是评估UnaryExpression的结果。
  2. Return ToNumber(GetValue( expr )). 返回ToNumber(GetValue( expr ))。

Yes it will make sure it is int (or a number in general as @Felix says). 是的,它会确保它是int(或者@Felix所说的一般数字)。 Try this code out: 试试这个代码:

var i = "2";
console.log(i === 2); // false
console.log(+i === 2); // true

Yes, applying the unary + to a variable ensures that if it's some other type (a string, for instance), it gets converted to a number (not an int, JavaScript doesn't have ints although it uses them internally for some operations). 是的,将一元+应用于变量可确保如果它是某种其他类型(例如字符串),它会转换为数字 (不是int,JavaScript没有整数,尽管它在内部使用它们进行某些操作) 。 The number can be fractional, and if it's a string it's parsed in the usual way JavaScript parses numbers (so for instance, +"0x10" is 16 decimal). 数字可以是小数,如果它是一个字符串,它会以通常的方式解析JavaScript解析数字(例如, +"0x10"是十进制的16 )。

+i确保我被解析成一个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM