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。我能做得更好吗?
当前回答
是的,它的建议现在是第四阶段。这意味着该提案已准备好纳入正式的ECMAScript标准。您已经可以在Chrome、Edge和Firefox的最新桌面版本中使用它,但我们需要等待一段时间,直到该功能达到跨浏览器的稳定性。
查看以下示例以演示其行为:
//注意:只有在运行上述浏览器的最新版本时,这才有效const var1=未定义;const var2=“回退值”;常量结果=var1??var2;console.log(`${result}`中的空合并结果);
上一示例等效于:
const var1=未定义;const var2=“回退值”;常量结果=(var1!==null&&var1!===undefined)?变量1:var2;console.log(`${result}`中的空合并结果);
请注意,无效合并不会像||运算符那样威胁虚假值(它只检查未定义的值或空值),因此下面的代码片段将如下所示:
//注意:只有在运行上述浏览器的最新版本时,这才有效常量var1=“”;//空字符串const var2=“回退值”;常量结果=var1??var2;console.log(`${result}`中的空合并结果);
对于TypesScript用户,从TypeScript 3.7开始,该功能现在也可用。
其他回答
是的,它很快就要来了。请参阅此处的提案和此处的实施状态。
它看起来像这样:
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
如果||作为C#??的替代品??在您的情况下还不够好,因为它包含空字符串和零,所以您可以始终编写自己的函数:
function $N(value, ifnull) {
if (value === null || value === undefined)
return ifnull;
return value;
}
var whatIWant = $N(someString, 'Cookies!');
我试图检查输入是否为空,然后相应地使用该值。这是我的密码。
let valueToBeConsidered = !inputValue ? "trueCondition" : "falseCondition",
因此,如果inputValue为空,则valueToBeConsidered=false条件;如果inputValue具有值,则valuetoBeConsided=true条件
这里有两项:
逻辑或
const foo=“”|“默认字符串”;
console.log(foo);//输出为“默认字符串”
空合并运算符
常量foo=''??'默认字符串';
console.log(foo);//输出为空字符串,即“”
零合并运算符(??)是一种逻辑运算符,当左侧操作数为空或未定义时,它返回右侧操作数,否则返回左侧操作数。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
ECMAScript 2021启用了两个新功能:
空合并运算符(??),是一种逻辑运算符,当左侧操作数为空或未定义时,返回右侧操作数,否则返回左侧操作数。
设b=未定义??5.console.log(b);//5.
逻辑零赋值(x??=y)运算符,仅在x具有零值(空或未定义)时赋值。
常量车={速度:20};车速??=5.控制台日志(轿厢速度);汽车名称??=“雷诺”;console.log(car.name);
有关逻辑零赋值的更多信息,请参阅此处https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment
有关空合并运算符的更多信息,请参阅此处https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator