繁体   English   中英

有没有更好的方法在 javascript if 语句中“什么都不做”?

[英]Is there a better way to 'do nothing' in javascript if statement?

我的网址看起来像这样 = https://studentscafe.com/menu/2

我正在尝试检查它是否有 2 个不同的 url 参数...

1.) ?dinner=1

或者

2.) &dinner=1

如果 #1 存在,则什么都不做

如果 #2 存在,则什么都不做

但如果两者都不存在,则默认将?dinner=1添加到 url。

有没有更好的方法让默认值在 if 语句中不做任何事情? 例如在这里小提琴

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 : 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';
}

使用正则表达式! 否定运算符,这可以相当简单:

 var path = 'https://studentscafe.com/menu/2'; if (!/[?&]dinner=1/.test(path)) { path += '?dinner=1'; } console.log(path);

你可以这样做。

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';
}

在现代 JS 中,您可能只是喜欢

['?dinner=1','?dinner=2'].every(s => !path.includes(s)) && (path += '?dinner=1');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM