Вопрос

eq: function( i ) {
    var len = this.length,
        j = +i + ( i < 0 ? len : 0 );
    return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},

i'm new to programming in general, but what is the purpose of having a single + sign infront of an expression, i've seen these in jquery library a lot.

+(expression)

these i'd understand, as they are negative:

-(1);// -1
Это было полезно?

Решение

It converts the string number to actual number in the expression.

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

Quoting from the ECMA 5.1 Standard Specifications for + operator,

The unary + operator converts its operand to Number type.

Internally, a JavaScript string will be converted to a number based on these rules specified in the ECMA 5.1 standards.

Edit: As per the Number specifications, it also internally uses the same ToNumber to convert its parameter to a number. So, technically Number(<number string>) is the same as +<number string>.

Другие советы

It is used to convert a value to a floating point number.

+"123.25" + 2 = 125.25

Similar is

(x | 0)

that is instead used to conver to an integer (the operation is a bit-wise or with zero).

In asm.js can these forms are used also as type declarations for parameters and locals.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top