我的网址看起来像这样 = https://studentscafe.com/menu/2
我正在尝试检查它是否有 2 个不同的 url 参数...
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
最佳答案
代替
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';
}
关于javascript - 在javascript if语句中有没有更好的方法来处理 'do nothing'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42397297/