之间的区别和??运营商
??和||在 JS 中有什么区别
const a = {}
const b = a.name ?? 'varun 1'
console.log(b)
const d = a.name || 'varun 2'
console.log(d)
回答
主要区别在于,nullish coalescing(??)仅当左操作数是null或 时,运算符才会将结果作为右操作数给出undefined。
而OR (||)运算符会将结果作为左操作数的所有假值的右操作数。
下面是一些例子
- 代码段 1:
0作为输入
const a = 0;
//a || 10 --> Will result in 10, as || operator considers it as falsy value and resulting the right side operand
console.log(`a || 10 = ${a || 10}`);
//a ?? 10 --> Will result in 0, as ?? operator consider it as truthy value and resulting the left side operand
console.log(`a ?? 10 = ${a ?? 10}`);
- 代码段 2:
''作为输入
const a = ''
console.log(`a || "ABC" = ${a || "ABC"}`);
console.log(`a ?? "ABC" = ${a ?? "ABC"}`);
- 代码段 3:
null作为输入
const a = null;
console.log(`a || 10 = ${a || 10}`);
console.log(`a ?? 10 = ${a ?? 10}`);
- 代码段 4:
undefined作为输入
const a = {}
//Here a.name will be undefined, hence both of the operands results the right side operand
console.log(`a.name ?? 'varun 1' = ${a.name ?? 'varun 1'}`);
console.log(`a.name || 'varun 2' = ${a.name || 'varun 2'}`);
const a = {name: ''}
//As, here a.name will be '' then
//?? will result ''
console.log(`a.name ?? 'varun 1' = ${a.name ?? 'varun 1'}`);
//|| will result in varun 2
console.log(`a.name || 'varun 2' = ${a.name || 'varun 2'}`);
- 片段 5:
false作为输入
const a = false;
console.log(`a || 10 = ${a || 10}`);
console.log(`a ?? 10 = ${a ?? 10}`);
如上所述,当输入为null或时,两个运算符的行为相似undefined。当我们提供falsy诸如0, '', false, 之类的值时,我们将看到真正的区别NaN。