我知道一个if语句可以很容易地做到这一点。我只是想知道是否有任何事情可以做得更简单。
例如:
var a
var b='this has a value'
var c = don't use a, instead use b
答案 0 :(得分:4)
如果a
(如果已定义)是真实的,请选择:
var c = a || b;
let a1;
let b1 = 5;
let c1 = a1 || b1;
console.log(c1);
let a2 = 'truthy';
let b2 = 10;
let c2 = a2 || b2;
console.log(c2);
否则,如果可以定义a
但为假,请使用条件运算符:
var c = a !== undefined ? a : b;
let a1 = null;
let b1 = 5;
let c1 = a1 !== undefined ? a1 : b1;
console.log(c1);