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

谁都会走 提交于 2019-12-12 06:33:48

问题


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.

回答1:


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>


来源:https://stackoverflow.com/questions/33592385/if-0-in-array-is-this-even-legal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!