What does a + prefix do in this context?

后端 未结 5 745
栀梦
栀梦 2021-01-27 04:23

Here is a line of code from underscore. What is that plus prefix for in this line?

if (obj.length === +obj.length) { // plus prefix?
5条回答
  •  不知归路
    2021-01-27 04:35

    Adding a + symbol effectively converts a variable into a number, such that:

    +"1" === 1;
    

    However, please note that

    +"1" === "1"; // FALSE
    +"1" ==  "1"; // TRUE
    

    This is because == will convert its operands to the same type, whereas === will not.

    That means that the test:

    obj.length === +obj.length
    

    Is essentially trying to test whether obj.length is numeric.

    In Underscore, this code is trying to figure out if a variable of unknown type has a property called length and whether it is numeric. The assumption is that, if these are both true, you can iterate over the variable is if it were an array.

    EDIT

    Please note, the OP's code has a number of bugs in it, not least of which is this approach to detecting if something is an Array (or Arraylike). The following object would cause problems:

    var footballField = {
        covering: "astroturf",
        condition: "muddy",
        length: 100
    };
    

    I'm not advocating the above approach... just explaining someone else's.

提交回复
热议问题