-->

Most concise way to assign a value from a variable

2020-08-11 04:46发布

问题:

Anyone knows of a more concise/elegant way of achieving the following?

A = B if B?

Thanks.

EDIT:

I'm looking for a solution that references A and B once only. And would compile to
if (typeof B !== "undefined" && B !== null) { A = B; }
or something else similar.

To have this short helps have the following a bit more readable:
someObject[someAttribute] = (someOtherObject[someOtherAttribute] if someOtherObject[someOtherAttribute]?)
That is the motivation for my question.

回答1:

You could say:

a = b ? a

For example, this:

a = 11
a = b ? a
console.log(a)
b = 23
a = b ? a
console.log(a)​

will give you 11 and 23 in the console (demo: http://jsfiddle.net/ambiguous/ngtEE/)



回答2:

Maybe something like:

A=_ if (_=B)?

expanded:

if ((_ = B) != null) {
  A = _;
}

This will overwrite A with what ever is in B, but only if it is not null, referencing both only once.



回答3:

Not sure about Coffee Script but you can use the OR operator for this in regular javascript like so:

a = b || a