【问题标题】:cleaner way to check whether or not a the current window.location.href is equal to any of the strings in the array更简洁的方法来检查当前 window.location.href 是否等于数组中的任何字符串
【发布时间】:2022-02-11 02:07:29
【问题描述】:

如果 url 等于以下 url 数组中的任何字符串,我会尝试进行重定向:

所以我做了以下

function redirectUser() {
  if (window.location.href === 'https://swish.com/login' || window.location.href === 'https://swish.com/register' || window.location.href === 'https://swish.com/overview') {
    window.location.replace('https://swish.com/onboard');
  }
}

但这有点难看,所以我想把网址放在一个数组中,然后做这样的事情:

function redirectUser() {
  const urls = ['https://swish.com/login', 'https://swish.com/register', 'https://swish.com/overview' ]
for(let url of urls) {
  if (window.location.href === url) {
    window.location.replace('https://swish.com/onboard');
  }
 }
}

还有其他方法可以做到这一点吗?如果不是,您认为哪个是更好的选择?谢谢!

【问题讨论】:

  • if(urls.includes(window.location.href)) redirect

标签: javascript reactjs dom ecmascript-6 href


【解决方案1】:

我觉得对你有帮助

   function redirectUser() {
     const urls = ['https://swish.com/login', 'https://swish.com/register', 
      'https://swish.com/overview' ]
         if(urls.includes(window.location.href)){
         window.location.replace('https://swish.com/onboard');
        }
     }  

【讨论】:

    【解决方案2】:

    您似乎已经在代码中静态地拥有了所有字符串。所以你可以尝试使用switch,它的性能比ifcheck here更快。
    如果您通过某种逻辑来重现字符串,那么您还可以选择更快的 Regular Expressions。否则,您可以坚持使用数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-24
      • 2011-04-03
      • 2017-10-21
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2011-08-08
      相关资源
      最近更新 更多