javascript operator “in”

前端 未结 5 918
渐次进展
渐次进展 2021-01-25 00:56

I\'m used to python, so

a = [1,2,3]
1 in a # -> True
b = [\"1\", \"2\", \"3\", \"x\"]
\"x\" in b # -> True

Why is it that in JavaScript

5条回答
  •  情歌与酒
    2021-01-25 01:30

    The thing you have to understand about JavaScript is almost everything is an "Object" that can have properties. Array's are just a special type of object whose properties are integer indexes and have push, pop, shift, unshift, etc. methods. Plus they can be defined with the square bracket shorthand you used:

    a = [1,2,3];
    

    This creates an Array object with the properties:

    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    

    Now as others have said, all the in operator does is check that an object has a property of that name and a[1] == 2 therefore 1 in a == true. On the other hand,

    b = ["1", "2", "3", "x"];
    

    created an Array object with the properties:

    b[0] = "1";
    b[1] = "2";
    b[2] = "3";
    b[3] = "x";
    

    So b["x"] == undefined therefore "x" in b == false.

    The other thing you have to understand is JavaScript uses "duck typing", meaning if it looks like a number, JavaScript treats it like a number. In this case, b["1"] == 2 therefore "1" in b == true. I'm not 100% certain whether this is duck typing at work or JavaScript just always treats property names as Strings.

    If you wanted to declare a generic object that wouldn't have the Array methods but had the same properties you would write:

    var b = {"0": "1", "1": "2", "2": "3", "3": "x"};
    

    Which is shorthand for:

    var b = {}; // This declares an Object
    b[0] = "1";
    b[1] = "2";
    b[2] = "3";
    b[3] = "x";
    

提交回复
热议问题