Is there a way to write the JavaScript code below as a one-liner?
this.isContactPage = (window.location.pathname === '/contact');
if (!this.isContactPage) return false;
The method continues on if this.isContactPage
is true.
The property this.isContactPage
is needed in other places in the script.
return !(this.isContactPage = (window.location.pathname === '/contact'));
Another example:
console.log(window.prop); // undefined
console.log(!(window.prop = true) || undefined); // undefined
console.log(!(window.prop = true)); // false
console.log(window.prop); // true
It'll be fairly dense and "obscured" code, but you can inline assignments in conditionals:
if ( !this.isContactPage = ( window.location.pathname == '/contact' ) ) return false;
This will only return the function if this.isContactPage
is assigned the value false
otherwise the function is not returned and continues on execution, as opposed to:
return ( this.isContactPage = ( window.location.pathname == '/contact' ) );
Which will return true
or false
immediately.
return !this.isContactPage = (window.location.pathname === '/contact')
with this you will not have errors!
this.isContactPage = /contact/gi.test(window.location.pathname);
if (!this.isContactPage) return false;
or
return !(/contact/gi.test(window.location.pathname))
I have something makes your code as short as possible!
return !(this.isContactPage=location.pathname=='/contact')
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.