带有返回声明的单行
One-Liner with Return Statement
有没有办法将下面的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' ) );
这将立即返回true
或false
。
return !this.isContactPage = (window.location.pathname === '/contact')
我有一些东西让你的代码尽可能短!
return !(this.isContactPage=location.pathname=='/contact')
- 你不需要"窗口"
- 您不需要直接通过代码返回 false 或 true
- 您不需要 ===,然后将其更改为 ==建议的最短方式有 88 个字母,而这个建议只有 68 个字母,更具可读性和可理解性!
有了这个,你就不会有错误了!
this.isContactPage = /contact/gi.test(window.location.pathname);
if (!this.isContactPage) return false;
或
return !(/contact/gi.test(window.location.pathname))
相关文章:
- Dojo不解析自定义小部件的模板html中的小部件声明性
- 直接在函数声明上使用function.prototype.bind
- 获取HTML属性中CSS声明的值
- 对API数据使用声明性绑定
- 可以Resharper在我的javascript函数声明中添加分号
- 如何为排除无穷大和NaN的数字声明Flow类型
- 此行是否包含函数声明
- Javascript以不同的方式声明数字
- 如何使用php文件中的GET来获取我在.js文件中声明的变量
- 使用同一对象中的其他变量声明变量
- 如何在AngularJS工厂中正确声明对象属性
- 用||声明变量
- 其中的用例标签'的声明
- 如何将变量声明为全局变量
- 调用函数中声明的变量
- 一个'var'在函数内部声明
- 我应该如何声明我的自调用函数
- 使用在函数外部声明的变量的 Javascript 返回值 + undefined
- 带有返回声明的单行
- 在单行中声明多个变量+Angular 2&TypeScript