Reputation: 680
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?
Upvotes: 2
Views: 6587
Reputation: 1075059
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).
Upvotes: 2
Reputation: 21713
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
Upvotes: 2
Reputation: 816790
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
Upvotes: 5
Reputation: 385274
Almost, but any number is fine.
[ECMA-262: 11.4.6]:
The unary+
operator converts its operand toNumber
type.The production UnaryExpression : + UnaryExpression is evaluated as follows:
- Let expr be the result of evaluating UnaryExpression.
- Return ToNumber(GetValue(expr)).
Upvotes: 3