javascript - 在javascript if语句中有没有更好的方法来处理 'do nothing'?

标签 javascript

我的网址看起来像这样 = 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/

相关文章:

javascript - 将 Chrome 应用程序移植到 UWP : How to handle "background page"?

javascript - 用php获取jsFiddle结果iframe源码

javascript - 未捕获的类型错误 : Cannot set property '_DT_CellIndex' of undefined Datatables

javascript - 在 Javascript 函数中未将表达式赋值给值是否合法?

javascript - 生成多维动态javascript数组

javascript - 如何阻止值变为负值

javascript - 使用 JS 或 jQuery 从 DOM 中完全删除元素/标签?

javascript - 如何跟踪JavaScript执行性能?

javascript - 是否可以使用用户先前选择的内容重新填充文件选择表单字段

javascript - 使用调用者组件的相同属性