【问题标题】:jQuery.type() is deprecated. When checking if a var is not an object, what should I use instead? [duplicate]jQuery.type() 已弃用。检查 var 是否不是对象时,我应该使用什么来代替? [复制]
【发布时间】:2020-09-27 23:20:33
【问题描述】:

jQuery.type() is deprecated in jQuery 3.3 and above. 在重构使用此 API 的旧代码时,我应该使用什么来代替 jQuery.type()?

例如,我的页面所依赖的插件之一使用 $.type() API,如下所示。

if ($.type(button) !== 'object') {
     throw new Error('button with key "' + key + '" must be an object');
}

我想用未弃用的东西替换它。

【问题讨论】:

  • 好吧,只是去掉变量名,可能是!button || !button.tagName || button.tagName !== 'BUTTON'
  • j11y.io/jquery/#v=1.11.2&fn=jQuery.type 你也可以看看源代码,看看他们在做什么

标签: jquery


【解决方案1】:

从您的链接中,我点击了折旧版本并到达这里:https://api.jquery.com/category/version/3.3/

让我点击发行说明链接:https://blog.jquery.com/2018/01/19/jquery-3-3-0-a-fragrant-bouquet-of-deprecations-and-is-that-a-new-feature/

我在哪里找到了 github 提交的更改: https://github.com/jquery/jquery/issues/3605 https://github.com/jquery/jquery/commit/1ea092a54b00aa4d902f4e22ada3854d195d4a18

他们贬低了这一点,因为“class2type”表没有处理新的数据类型,以至于没有用处。他们恢复了自己的内部代码以使用 vanilla js typeof - 我认为这是您的代码库的预期更改。

另外,请参见此处:Difference between JQuery.type and typeof, which is faster 即在阅读某些类型时丢失细节的第二个答案。如果这对您来说有问题,我想这只是@Taplar 建议的那种解决方法/您对这个问题的回答(编辑/更新)。

【讨论】:

    【解决方案2】:

    看来,基于this response,你可以使用typeof yourVariable === 'object' && yourVariable !== null来判断一个变量是否是一个对象(注意,你还必须检查它不是null,因为JS认为null是对象。)

    由于如果button 变量不是对象,我们需要抛出错误,我们应该能够更改代码以使用typeof,如下所示:

    if (typeof button !== 'object' || typeof button === null) {
         throw new Error('button with key "' + key + '" must be an object');
    }
    

    (请注意,如果button var 为空,我们必须抛出错误,因为虽然 JavaScript typeof 将空值视为对象,但它不是我们要查找的对象类型。)

    简而言之,您需要将 jQuery.type() 替换为 typeof 比较。

    【讨论】:

    • 你也可以短路到未定义。 typeof (button || undefined) !== 'object'
    猜你喜欢
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2020-01-18
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多