简体   繁体   English

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

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

My url looks like this = https://studentscafe.com/menu/2我的网址看起来像这样 = https://studentscafe.com/menu/2

I'm trying to check whether or not it has 2 different url params...我正在尝试检查它是否有 2 个不同的 url 参数...

1.) ?dinner=1 1.) ?dinner=1

or或者

2.) &dinner=1 2.) &dinner=1

If #1 is present, do nothing如果 #1 存在,则什么都不做

If #2 is present, do nothing如果 #2 存在,则什么都不做

But if neither are present, default to adding ?dinner=1 to the url.但如果两者都不存在,则默认将?dinner=1添加到 url。

Is there a better way to have a default do nothing in an if statement?有没有更好的方法让默认值在 if 语句中不做任何事情? Fiddle here for example.例如在这里小提琴

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

Expected output: if the url doesn't have #1 or #2: https://studentscafe.com/menu/2?dinner=1预期输出:如果 url 没有 #1 或 #2: https://studentscafe.com/menu/2?dinner=1 : https://studentscafe.com/menu/2?dinner=1

Instead of代替

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

You can use您可以使用

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

In your case:在你的情况下:

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

Using a regular expression and the !使用正则表达式! negation operator, this can be rather simple:否定运算符,这可以相当简单:

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

You can do this way.你可以这样做。

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