我总是必须在没有任何东西的else条件中置null。有办法解决吗?
例如,
condition ? x = true : null;
基本上,有没有办法做到以下几点?
condition ? x = true;
现在它显示为语法错误。
供参考,这里有一些真实的示例代码:
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;
我总是必须在没有任何东西的else条件中置null。有办法解决吗?
例如,
condition ? x = true : null;
基本上,有没有办法做到以下几点?
condition ? x = true;
现在它显示为语法错误。
供参考,这里有一些真实的示例代码:
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;
当前回答
我们现在也有了“null coalescing operator”(??)。它的工作原理类似于“OR”操作符,但仅在左侧表达式为空或未定义时返回,对于其他假值则不返回。
例子:
const color = undefined ?? 'black'; // color: 'black'
const color = '' ?? 'black'; // color: ''
const color = '#ABABAB' ?? 'black'; // color: '#ABABAB'
其他回答
要在数组或对象声明中使用三元操作符而不使用else,你可以使用ES6展开操作符…():
const cond = false;
const arr = [
...(cond ? ['a'] : []),
'b',
];
// ['b']
对于对象:
const cond = false;
const obj = {
...(cond ? {a: 1} : {}),
b: 2,
};
// {b: 2}
原始来源
你可以这样写
x = condition ? true : x;
当条件为假时,x未被修改。
这就等于
if (condition) x = true
编辑:
!defaults.slideshowWidth
? defaults.slideshowWidth = obj.find('img').width()+'px'
: null
有几个选择——我不是说这些更好/更坏——只是选择
传入null作为第三个参数可以工作,因为现有值为空。如果您重构并更改条件,那么就会有这种情况不再成立的危险。在三元中传入现有值作为第二个选择可以防止这种情况:
!defaults.slideshowWidth =
? defaults.slideshowWidth = obj.find('img').width()+'px'
: defaults.slideshowwidth
更安全,但可能不那么好看,而且打字更多。实际上,我可能会写
defaults.slideshowWidth = defaults.slideshowWidth
|| obj.find('img').width()+'px'
var x = condition || null;
我们现在也有了“null coalescing operator”(??)。它的工作原理类似于“OR”操作符,但仅在左侧表达式为空或未定义时返回,对于其他假值则不返回。
例子:
const color = undefined ?? 'black'; // color: 'black'
const color = '' ?? 'black'; // color: ''
const color = '#ABABAB' ?? 'black'; // color: '#ABABAB'
简单的方法是:
if (y == x) z;