繁体   English   中英

foo in bar-'in'运算符JavaScript?

[英]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是具有值的数组的数字索引或foo是其他属性或方法名,则bar中的foo in bar将为true。

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

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

in运算符用于检查数组或对象中是否存在 ,例如

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实例,该实例包含活动浏览器中每个受支持的样式属性的属性。

您在帖子中提供的代码段检查查看的浏览器是否支持该样式的某些版本(正式版本或带有多个常见供应商前缀之一)。

 document.createElement('div').style

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM