`if (0 in array)` — is this even legal?

For now I'm writing a complex of laboratory works about coding in JavaScript. I know that there is a construction like

if ('field' in object) {
    /* Do something with object.field */
}

to be used to determine that a variable called field really exists in object even if it equals to undefined.

And my Firefox Developer Edition 44 is able to determine if there is a field in an array like this:

if (0 in array) {
    /* Do something with first element */
}

The question : is this method legal? Is it a part of a living standard or not?


What it is supposed to do :
Let q be an array with such elements:

[ 5, <1 empty slot>, undefined, 5 ]

Then:

  • 0 in q , 2 in q , 3 in q equals to true ;
  • 1 in q equals to false .

  • if (0 in array) — is this even legal?

    Sure. The in operator checks to see if a property exists in the object (directly, or via the prototype chain). The left-hand operand is the name of the property, the right-hand operand is the object to check. If the left-hand operand isn't a string or Symbol , it's coerced to a string. This is all completely within the specification:

  • The in operator (scroll down to RelationalExpression : RelationalExpression in ShiftExpression)

  • The abstract ToPropertyKey operation

  • The abstract HasProperty operation

  • JavaScript's untyped arrays are objects (and not really arrays, although engines optimize that when they can). Array indexes are property names (and technically strings, though engines optimize that when they can). So you can use in to check if an array contains a property by using an "array index" with in and the array. (You can also use hasOwnProperty : theArray.hasOwnProperty(0) , but it's slower with arrays on modern engines.)

    What it is supposed to do:

    Let q be an array with such elements:

    [ 5, <1 empty slot>, undefined, 5 ]
    

    Then:

  • 0 in q , 2 in q , 3 in q equals to true ;
  • 1 in q equals to false .
  • Yes, that's perfectly valid:

    var q = [];
    q[0] = 5;
    q[2] = undefined;
    q[3] = 5;
    for (var i = 0; i < q.length; ++i) {
      snippet.log(i + " in q? " + (i in q));
    }
    <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
    链接地址: http://www.djcxy.com/p/4692.html

    上一篇: 如何深度合并而不是浅层合并?

    下一篇: `如果(数组中的0)` - 这是否合法?