2017-02-22 109 views
0

我的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

+3

而是什麼都不做的,只是否定條件,失去了'else'塊:'if(path.indexOf('?dinner = 1')<1){...}' - 您可能還想指出,如果子字符串位於第一個位置,則indexOf可以返回'0' (索引0),所以'> = 1'可能應該是'> = 0'。 – Santi

+0

最好是使用<= - 1作爲條件 –

+0

如果這是對我的評論的迴應,否則我建議的'> = 0'的否定將是<<0,這與'<= -1'相同給定的上下文。 – Santi

回答

2

使用regular expression!否定運營商,這可能是相當簡單:

var path = 'https://studentscafe.com/menu/2'; 
 

 
if (!/[?&]dinner=1/.test(path)) { 
 
    path += '?dinner=1'; 
 
} 
 

 
console.log(path);

3

而不是

if (something) { 
    // do nothing 
} else { 
    // do what you need 
} 

您可以使用

if (!something) { 
    // do what you need 
} 

你的情況:

if (path.indexOf('?dinner=1') == -1 && path.indexOf('&dinner=1') == -1) { 
    path = path + '?dinner=1'; 
} 
0

你可以這樣做。

var path = 'https://studentscafe.com/menu/2'; 

// Since there is no change to path if it contains either ?dinner=1 or &dinner=1 

if (path.indexOf('dinner=1') >= 1) { 
    console.log('has dinner'); 
    // do nothing leave url as it is 

} else { 
    path = path + '?dinner=1'; 
} 
相關問題