2

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?

Keith L.
  • 1,974
  • 11
  • 38
  • 64
Cynial
  • 648
  • 7
  • 20

5 Answers5

5

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

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
  • 1
    `slice` converts its arguments via the [ToInteger](http://es5.github.com/#x9.4) operation. (Basically, if handed a fractional numbers, it floors them.) – T.J. Crowder Mar 02 '12 at 12:51
3

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)).
Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
2

Yes it will make sure it is int (or a number in general as @Felix says). Try this code out:

var i = "2";
console.log(i === 2); // false
console.log(+i === 2); // true
Tim Rogers
  • 19,990
  • 6
  • 47
  • 66
2

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). 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).

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
0

+i makes sure that i is parsed into an number.

mas-designs
  • 7,160
  • 1
  • 27
  • 53
  • Wrong. `i+=i` increments the actual value +1! **NOT** `i=+i` -- http://www.devcurry.com/2011/07/unary-plus-operator-in-javascript.html – Smamatti Mar 02 '12 at 12:50
  • I had an syntax error. I deleted this as it also was not useful for the question. – mas-designs Mar 02 '12 at 12:51
  • @Smamatti:- i think you should check this:- http://stackoverflow.com/questions/5450076/whats-the-significant-use-of-unary-plus-and-minus-operators – Pranav Mar 02 '12 at 12:52
  • Just did a quick test in chrome. It works like parseFloat for positive and negative numbers. – Esben Skov Pedersen Mar 02 '12 at 12:53
  • @Pranav I don't see how this is related to the meaning of the incremental operator `+=` which **EvilP** used earlier. -- As you can see in the comment above, he edited his post due to this syntax error. – Smamatti Mar 02 '12 at 12:57
  • @Smamatti: Actually i did not look properly when i was writing comment.My Mistake... – Pranav Mar 02 '12 at 13:00