foo in bar - 'in' operator javascript?

前端 未结 4 2169
庸人自扰
庸人自扰 2021-01-21 09:52

I recently read a tutorial on CSS browser feature detection... The end product was something like this...

var prefix = [\'Moz\', \'webkit\', \'O\', \'ms\', \'Kht         


        
相关标签:
4条回答
  • 2021-01-21 10:27

    if (foo in bar) is used to check whether the value named foo is a property of the object bar. Since arrays are just specially treated objects, you are correct in assuming that it can be used to check for a value in an array.

    test_style = document.createElement('div').style returns an object with properties; since this is the case, you can use the foo in bar syntax to check it.

    0 讨论(0)
  • 2021-01-21 10:47

    The statement if (foo in bar) tests whether the object bar has a property named foo. It doesn't test for a property with the value foo.

    That is:

    var bar = {"a" : "x", "b" : "y"};
    alert("a" in bar); // true
    alert("x" in bar); // false
    

    You can use this syntax on arrays because they are a type of object. If bar is an array then foo in bar will be true if foo is either a numeric index of the array that has a value or if foo is some other property or method name.

    Also, if this is used to check values in an array HOW is test_style = document.createElement('div').style an array?

    test_style is an object, not an array.

    0 讨论(0)
  • 2021-01-21 10:48

    The in operator is used to check for the presence of a key in an array or object, e.g.

    3 in [1, 2, 3] // false, since the array indices only go up to 2
    2 in [1, 2, 3] // true
    'x' in { x: 5 } // true
    'toString' in Object.prototype // true
    

    The style property there is an instance of CSSStyleDeclaration, which contains properties for each supported style attribute in the active browser.

    The code snippet you gave in your post checks whether the viewing browser supports some version of that style (either the official one or with one of a number of common vendor prefixes).

    0 讨论(0)
  • 2021-01-21 10:51
     document.createElement('div').style
    

    will return a object which have CSS properties. you can use key in to check if particular property exist in a object.

    0 讨论(0)
提交回复
热议问题