【问题标题】:Simple substitute of assignment operators of logical ones in JavaScript?简单地替代 JavaScript 中逻辑运算符的赋值运算符?
【发布时间】:2014-01-12 04:22:21
【问题描述】:

JavaScript 有 assignment operators 对应于 arithmetic 的:+=-=*=/=%=

JavaScript 也有 assignment operators 对应于 bitwise 的:<<=>>=>>>=&=^=|=

但它没有assignment operators对应logical的:||=&&=

那么,我不能做类似的事情

aVeryLongVariableIdontWantToRepeat ||= 1;

this other question 解释了为什么 JS Java 没有这样的运算符。我想对于 JS 来说也是如此。

但我想知道是否有一种简单的方法可以模仿它们,避免

aVeryLongVariableIdontWantToRepeat = aVeryLongVariableIdontWantToRepeat || 1;

【问题讨论】:

  • 简单地缩短变量名怎么样?
  • 您链接到的另一个问题不是关于 JavaScript,而是关于 Java。
  • @T.J.Crowder 哦,真的
  • @p.s.w.g 我不能缩短像CanvasRenderingContext2D.prototype.clear这样的东西
  • @Oriol var p = CanvasRenderingContext2D.prototype; p.clear = p.clear || ...?

标签: javascript operators logical-operators assignment-operator substitution


【解决方案1】:

不,没有。我觉得这个答案应该有更多,但实际上就是这样。 a = a || x 的最短版本是……a = a || x

【讨论】:

  • 还有a = a? a : x,不过有点长。
【解决方案2】:

没有更短的方法:a = a || 1 是最简单的方法。

但是,为了避免不必要的赋值(稍微牺牲可读性),您也可以使用a || ( a = 1)

JSFIDDLE

var a,b='x';
a || ( a = 1 );
b || ( b = 2 );
console.log( a + ', ' + b ); // Outputs "1, x"

【讨论】:

  • 当然,a || (a = 1) 不比a = a || 1 短,我们可以指望引擎不会在无效任务上浪费时间。
【解决方案3】:

它可能会帮助您研究使用 Coffeescript 编写代码,它具有可用的 ||= 运算符。

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 2018-12-18
    • 1970-01-01
    • 2011-09-10
    • 2017-11-06
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多