Foo in baR语言 'in' operator JavaScript?



我最近阅读了有关CSS浏览器功能检测的教程...最终产品就是这样...

var prefix = ['Moz', 'webkit', 'O', 'ms', 'Khtml'],
    test_style = document.createElement('div').style;
var css_check = function(prop) {
    if (prop in test_style) {
        return true;
    }
    for (var i = 0; i < prefix.length; i++) {
        if (prefix[i] + prop in test_style) {
            return true;
        }
    }
    return false;
};
css_check('whatev_css_property');

我不明白的部分是...

if (prop in test_style)if (foo in bar)

根据我阅读的内容,使用if (foo in bar)来检查一个值是否在数组中,但我可能在这里错了,我没有发现太多的文档。另外,如果用于检查数组中的值,则test_style = document.createElement('div').style是如何数组?没有意义...

我很困惑。任何澄清都将不胜感激。

语句if (foo in bar)测试对象bar是否具有名为 foo的属性。它不会测试具有值foo的属性。

是:

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

您可以在数组上使用此语法,因为它们是一种对象。如果bar是数组,则foo in bar如果foo是具有值的数字索引,或者foo是其他属性或方法名称。

另外,如果用于检查数组中的值,test_style = document.createElement('div').style数组如何?

test_style是一个对象,而不是数组。

in操作员用于检查数组或对象中的A ,例如

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

style属性有一个CSSStyledEclaration的实例,该实例包含Active浏览器中每个受支持的样式属性的属性。

您在帖子中给出的代码段检查是否支持某种版本的样式(官方的浏览器或具有许多普通供应商前缀之一)。

if (foo in bar)用于检查名为foo的值是否是对象bar的属性。由于数组只是经过特殊处理的对象,因此您可以在数组中检查一个值,您是正确的。

test_style = document.createElement('div').style返回具有属性的对象;由于是这种情况,您可以使用foo in bar语法对其进行检查。

 document.createElement('div').style

将返回具有CSS属性的对象。您可以使用key in检查对象中是否存在特定属性。

最新更新