简体   繁体   English

如何在 Javascript 中实现三元赋值?

[英]How does one achieve ternary assignment in Javascript?

I would like to do a reassignment of a class variable in Javascript (or Typescript) using a ternary operator.我想使用三元运算符在 Javascript(或 Typescript)中重新分配类变量。 The reassignment of this.foo depends on the current value of this.foo which I can update with the following:的重新分配this.foo取决于电流值this.foo ,我可以与以下更新:

setFoo = () => {
    this.foo = this.foo ? "" : "foo";
}

However, I am wondering if I can do reassignment of this.foo without writing this.foo twice.不过,我想知道如果我能做到的再分配this.foo无需编写this.foo两次。 This would be helpful because I am trying to dynamically update classes on an Angular component (written in Typescript).这会很有帮助,因为我正在尝试动态更新 Angular 组件(用 Typescript 编写)上的类。

I would like to be able to write something like the following which makes use of truthy/falsy values.我希望能够使用真/假值编写如下内容。 If this.foo is truthy, then "" is assigned;如果this.foo为真,则分配"" otherwise, "foo" is assigned:否则,分配"foo"

setFoo = () => {
    this.foo =? "" : "foo";
}

I have tried searching for similar questions but could not find an answer.我曾尝试搜索类似的问题,但找不到答案。 My initial thought was to use the ??= operator in Typescript 4.0 but I do not think it will work.我最初的想法是在 Typescript 4.0 中使用 ??= 运算符,但我认为它行不通。 Perhaps my ideal solution does not exist because it could be a bad programming habit.也许我的理想解决方案不存在,因为它可能是一个糟糕的编程习惯。 Thanks谢谢

Great question.很好的问题。 Unfortunately this is not possible .不幸的是,这是不可能的 There is a shorthand version that some people use, but it still includes a duplication:有一些人使用的速记版本,但它仍然包含重复:

foo = foo || otherCondition;

So the shorthand of a shorthand, not too useful in my opinion.所以速记的速记,在我看来不是太有用。

Short answer : I'd go with the normal ternary.简短回答:我会选择普通的三元。

您必须使用 IF ELSE 而不是使用三元语句,if else 将使您更好地控制在它下编写的语句并且使用效率更高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM