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