Javascript Shorthanding

Javascript Shorthanding

本文关键字:Shorthanding Javascript      更新时间:2023-09-26

考虑以下示例:

if (cache) {
    x = cache;
} else {
    x = cache = someMethod();
}

无论如何,让它比cache ? x = cache : x = cache = someMethod();短?

编辑:

感谢所有提出的解决方案,我应该注意到,有问题的数据是字符串而不是布尔值。

x = cache || (cache = someMethod());

如果不确定之前是否声明和/或分配了cache,这是对MaxArts答案的修正(使用短路布尔求值和逗号运算符):

x = (cache = window.cache || someMethod(),cache);
//note: 'window' may be another namespace

在严格模式下,这也不起作用。在这种情况下,这将:

'use strict';
var x = function(w){w.cache = w.cache || someMethod(); return w.cache;}(window);

实现这一点的干净方法(即使使用bools也可以)是

   if (cache === undefined) { cache = someMethod (); }
   x = cache;