带有返回声明的单行

One-Liner with Return Statement

本文关键字:单行 声明 返回      更新时间:2023-09-26

有没有办法将下面的JavaScript代码编写为单行代码?

this.isContactPage = (window.location.pathname === '/contact');
if (!this.isContactPage) return false;

如果 this.isContactPage为 true,则该方法将继续。

脚本中的其他位置需要属性this.isContactPage

return !(this.isContactPage = (window.location.pathname === '/contact'));

再比如:

console.log(window.prop); // undefined
console.log(!(window.prop = true) || undefined); // undefined
console.log(!(window.prop = true)); // false
console.log(window.prop); // true

它将是相当密集且"模糊"的代码,但您可以在条件中内联赋值:

if ( !this.isContactPage = ( window.location.pathname == '/contact' ) ) return false;

仅当this.isContactPage被赋值时,这将返回函数false否则不会返回该函数并在执行时继续,而不是:

return ( this.isContactPage = ( window.location.pathname == '/contact' ) );

这将立即返回truefalse

return !this.isContactPage = (window.location.pathname === '/contact')

我有一些东西让你的代码尽可能短!

return !(this.isContactPage=location.pathname=='/contact')
  1. 你不需要"窗口"
  2. 您不需要直接通过代码返回 false 或 true
  3. 您不需要 ===,然后将其更改为 ==建议的最短方式有 88 个字母,而这个建议只有 68 个字母,更具可读性和可理解性!

有了这个,你就不会有错误了!

this.isContactPage = /contact/gi.test(window.location.pathname);
if (!this.isContactPage) return false;

return !(/contact/gi.test(window.location.pathname))