如果 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');
}
}
}
有沒有其他方法可以做到這一點?如果不是,您認為哪個是更好的選擇?謝謝!
uj5u.com熱心網友回復:
我想它會幫助你
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');
}
}
uj5u.com熱心網友回復:
看來您已經在代碼中靜態地擁有了所有字串。因此,您可以嘗試使用switch哪種性能方面比if 此處檢查更快。
如果您通過某種邏輯來重現字串,那么您還可以選擇更快的正則運算式。否則,您可以堅持使用陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426149.html
標籤:javascript 反应 dom ecmascript-6 链接
