Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "i = +i" mean in Javascript?

In jquery source:

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?

like image 831
Cynial Avatar asked May 18 '26 00:05

Cynial


2 Answers

Is it used for make sure parse i to int?

No, it is to make sure that i is a number (either float or int). 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.

More information: MDN - Arithmetic Operators

like image 99
Felix Kling Avatar answered May 20 '26 13:05

Felix Kling


Almost, but any number is fine.

[ECMA-262: 11.4.6]: The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Return ToNumber(GetValue(expr)).
like image 36
Lightness Races in Orbit Avatar answered May 20 '26 13:05

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!