【问题标题】:What benefit does using `in` have over object.prop?使用 `in` 比 object.prop 有什么好处?
【发布时间】:2014-01-28 04:15:39
【问题描述】:

我们都看到该功能检测到执行以下操作:

var touch = function () {
  return 'ontouchstart' in window;
};

但我想知道使用in 运算符是否有其他好处(这样可以节省几个字节)?

var touch = function () {
  return !!window.ontouchstart;
};

使用in还有其他好处吗?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    两者完全不同。

    当你这样做时

    !!window.ontouchstart
    

    您正在检查window.ontouchstart 的值是否为truthy,但是

    'ontouchstart' in window
    

    检查ontouchstart 是否存在于window 对象中。

    另一个问题使用!!window.ontouchstart 来检查成员是否存在是,即使ontouchstart 存在并且如果它具有虚假值,例如undefinednull、@987654331 @ 或 0,它仍然会返回 false。因此,它不应该用于检查成员是否存在。

    【讨论】:

    • 谢谢,很有道理!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多