简体   繁体   English

检查是否支持可选链接

[英]Check if optional chaining is supported

I want to use a polyfill for optional chaining but I do not want to provide a polyfill for browsers which already support this feature.我想使用 polyfill 进行可选链接,但我不想为已经支持此功能的浏览器提供 polyfill。

Is there a way to determine whether a browser supports optional chaining?有没有办法确定浏览器是否支持可选链接?

I couldn't find any solutions online.我在网上找不到任何解决方案。 I managed to come up with this:我设法想出了这个:

const getIsOptionalChainingSupported = () => {
  try {
    const test = {};
    const isUndefined = test?.foo?.bar
    if (isUndefined === undefined) {
      return true
    }
  } catch {
    return false
  }
}

This works:这有效:

const isOptionalChainingSupported = () => {
  try {
    const foo = {};

    eval('foo?.bar');
  } catch {
    return false;
  }

  return true;
}

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

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