Javascript中是否有空合并运算符?

例如,在C#中,我可以这样做:

String someString = null;
var whatIWant = someString ?? "Cookies!";

我可以为Javascript找到的最佳近似是使用条件运算符:

var someString = null;
var whatIWant = someString ? someString : 'Cookies!';

这有点讨厌IMHO。我能做得更好吗?


当前回答

我试图检查输入是否为空,然后相应地使用该值。这是我的密码。

let valueToBeConsidered = !inputValue ? "trueCondition" : "falseCondition",

因此,如果inputValue为空,则valueToBeConsidered=false条件;如果inputValue具有值,则valuetoBeConsided=true条件

其他回答

在阅读了您的澄清之后,@Ates Goral的回答提供了如何在JavaScript中执行您在C#中执行的相同操作。

@Gumbo的答案提供了检查空值的最佳方法;然而,注意JavaScript中==与==的区别很重要,特别是在检查未定义和/或null时。

这里有一篇关于两个术语的区别的非常好的文章。基本上,请理解如果使用==而不是==,JavaScript将尝试合并正在比较的值,并在合并后返回比较结果。

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背景,这将是最自然的感觉解决方案。

使现代化

JavaScript现在支持空值合并运算符(??)。当左侧操作数为空或未定义时,它返回右侧操作数,否则返回左侧操作数。

旧答案

使用前请检查兼容性。


与C#空合并运算符(??)等效的JavaScript使用逻辑OR(||):

var whatIWant = someString || "Cookies!";

在某些情况下(在下文中进行了澄清),这种行为与C#的行为不匹配,但这是在JavaScript中分配默认值/替代值的通用、简洁的方法。


澄清

无论第一个操作数的类型如何,如果将其转换为布尔值结果为false,则赋值将使用第二个操作数。注意以下所有情况:

alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)

这意味着:

var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"

请注意null的JavaScript特定定义。javascript中“无值”有两个定义。1.空:当变量为空时,表示该变量中不包含数据,但该变量已在代码中定义。这样地:

var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts

在这种情况下,变量的类型实际上是Object。测试它。

window.alert(typeof myEmptyValue); // prints Object

未定义:当一个变量之前没有在代码中定义,并且正如预期的那样,它不包含任何值。这样地:如果(myUndefinedValue==undefined){window.alert('it is undefined');}//警报

如果是这种情况,则变量的类型为“undefined”。

注意,如果您使用类型转换比较运算符(==),JavaScript将对这两个空值起同等作用。要区分它们,请始终使用类型严格比较运算符(==)。

是的,它很快就要来了。请参阅此处的提案和此处的实施状态。

它看起来像这样:

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