Javascript中是否有空合并运算符?
例如,在C#中,我可以这样做:
String someString = null;
var whatIWant = someString ?? "Cookies!";
我可以为Javascript找到的最佳近似是使用条件运算符:
var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
这有点讨厌IMHO。我能做得更好吗?
Javascript中是否有空合并运算符?
例如,在C#中,我可以这样做:
String someString = null;
var whatIWant = someString ?? "Cookies!";
我可以为Javascript找到的最佳近似是使用条件运算符:
var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
这有点讨厌IMHO。我能做得更好吗?
当前回答
注意,React的create-React-app工具链支持自3.3.0版(发布于5.12.2019)以来的空合并
可选的链接和空合并运算符我们现在支持可选的链接和无效合并运算符!//可选链接一(); // 如果“a”为空/未定义,则为undefinedbc、 //如果“b”为空/未定义,则未定义//空聚结未定义??'其他默认值';//result:'其他默认值'空??'其他默认值';//result:'其他默认值''' ?? '其他默认值';//结果:“”0 ?? 300; // 结果:0假的??真;//结果:false
也就是说,如果你使用create-react-app3.3.0+,你可以开始在你的react应用中使用空联合运算符。
其他回答
是的,它很快就要来了。请参阅此处的提案和此处的实施状态。
它看起来像这样:
x ?? y
实例
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
const undefinedValue = response.settings?.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings?.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings?.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings?.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings?.showSplashScreen ?? true; // result: false
需要支持旧浏览器并具有对象层次结构
body.head.eyes[0] //body, head, eyes may be null
可以使用此,
(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'
这里有两项:
逻辑或
const foo=“”|“默认字符串”;
console.log(foo);//输出为“默认字符串”
空合并运算符
常量foo=''??'默认字符串';
console.log(foo);//输出为空字符串,即“”
零合并运算符(??)是一种逻辑运算符,当左侧操作数为空或未定义时,它返回右侧操作数,否则返回左侧操作数。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
链接多个值/多个值
启用“短路”:如果第一个值之一有效,则不进行任何进一步评估这意味着顺序很重要,最左边的值优先
const value = first ?? second ?? third ?? "default";
function coalesce() {
var len = arguments.length;
for (var i=0; i<len; i++) {
if (arguments[i] !== null && arguments[i] !== undefined) {
return arguments[i];
}
}
return null;
}
var xyz = {};
xyz.val = coalesce(null, undefined, xyz.val, 5);
// xyz.val now contains 5
此解决方案与SQL联合函数类似,它接受任意数量的参数,如果它们都没有值,则返回null。它的行为类似于C#??运算符,即“”、false和0被视为NOT NULL,因此算作实际值。如果你来自.net背景,这将是最自然的感觉解决方案。