我的URL看起來像這樣= https://studentscafe.com/menu/2
有沒有更好的方法來'如果聲明在JavaScript'什麼都不做'?
我想,以檢查它是否具有2個不同的網址參數...
1)?dinner=1
或
2。 )&dinner=1
如果#1存在,什麼都不做
如果#2存在,什麼也不做
但是,如果都不存在,則默認爲將?dinner=1
添加到url。
有沒有更好的方法讓默認在if語句中什麼也不做?例如,Fiddle here。
var path = 'https://studentscafe.com/menu/2';
if (path.indexOf('?dinner=1') >= 1) {
console.log('has ?');
// do nothing leave url as it is
} else {
console.log('does not have ?');
if (path.indexOf('&dinner=1') >= 1) {
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}
}
預期輸出:如果URL沒有#1或#2:https://studentscafe.com/menu/2?dinner=1
而是什麼都不做的,只是否定條件,失去了'else'塊:'if(path.indexOf('?dinner = 1')<1){...}' - 您可能還想指出,如果子字符串位於第一個位置,則indexOf可以返回'0' (索引0),所以'> = 1'可能應該是'> = 0'。 – Santi
最好是使用<= - 1作爲條件 –
如果這是對我的評論的迴應,否則我建議的'> = 0'的否定將是<<0,這與'<= -1'相同給定的上下文。 – Santi