简体   繁体   中英

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

My url looks like this = https://studentscafe.com/menu/2

I'm trying to check whether or not it has 2 different url params...

1.) ?dinner=1

or

2.) &dinner=1

If #1 is present, do nothing

If #2 is present, do nothing

But if neither are present, default to adding ?dinner=1 to the url.

Is there a better way to have a default do nothing in an if statement? 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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