Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否有一个“问题”;“零合并”;JavaScript中的运算符?_Javascript_Operators_Null Coalescing Operator_Null Coalescing - Fatal编程技术网

是否有一个“问题”;“零合并”;JavaScript中的运算符?

是否有一个“问题”;“零合并”;JavaScript中的运算符?,javascript,operators,null-coalescing-operator,null-coalescing,Javascript,Operators,Null Coalescing Operator,Null Coalescing,Javascript中是否有空合并运算符 例如,在C#中,我可以这样做: String someString = null; var whatIWant = someString ?? "Cookies!"; 我能为Javascript找到的最佳近似值是使用条件运算符: var someString = null; var whatIWant = someString ? someString : 'Cookies!'; 这是有点恶心。我能做得更好吗?在阅读了您的说明之后,@Ates Gor

Javascript中是否有空合并运算符

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

String someString = null;
var whatIWant = someString ?? "Cookies!";
我能为Javascript找到的最佳近似值是使用条件运算符:

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

这是有点恶心。我能做得更好吗?

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

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


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

更新

JavaScript现在支持。当其左侧操作数为
null
undefined
时,它返回其右侧操作数,否则返回其左侧操作数

使用前请检查兼容性


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

在某些情况下(如下所述),行为与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"

注意特定于JavaScript的null定义。javascript中“无值”有两种定义。 1.Null:当变量为Null时,表示其中不包含任何数据,但该变量已在代码中定义。像这样:

var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts
if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
// alerts
x ?? y
在这种情况下,变量的类型实际上是Object。测试一下

window.alert(typeof myEmptyValue); // prints Object
  • 未定义:当一个变量以前没有在代码中定义过,并且正如预期的那样,它不包含任何值。像这样:

    var myEmptyValue = 1;
    myEmptyValue = null;
    if ( myEmptyValue === null ) { window.alert('it is null'); }
    // alerts
    
    if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
    // alerts
    
    x ?? y
    
  • 如果是这种情况,则变量的类型为“未定义”


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

    如果将
    |
    替换为C#
    在您的情况下不够好,因为它包含空字符串和零,您始终可以编写自己的函数:

     function $N(value, ifnull) {
        if (value === null || value === undefined)
          return ifnull;
        return value;
     }
    
     var whatIWant = $N(someString, 'Cookies!');
    
    函数合并(){
    var len=arguments.length;
    
    对于(var i=0;i这里没有人提到
    NaN
    ,对我来说,它也是一个空值。所以,我想我应该加上我的2美分

    对于给定代码:

    var a,
        b = null,
        c = parseInt('Not a number'),
        d = 0,
        e = '',
        f = 1
    ;
    
    如果要使用
    |
    运算符,则会得到第一个非false值:

    var result = a || b || c || d || e || f; // result === 1
    
    如果使用典型的合并方法,将得到
    c
    ,其值为:
    NaN

    var result = coalesce(a,b,c,d,e,f); // result.toString() === 'NaN'
    
    <>强>这两个词都不适合我。在我自己的聚合逻辑的小世界中,这可能与你的世界不同,我认为未定义的、空的和NANN都是“空的”。所以,我希望从合并方法中获得代码< D> <代码>(0)。 如果有人的大脑像我的一样工作,而你想排除NaN,那么这个方法可以实现:

    function coalesce() {
        var i, undefined, arg;
    
        for( i=0; i < arguments.length; i++ ) {
            arg = arguments[i];
            if( arg !== null && arg !== undefined
                && (typeof arg !== 'number' || arg.toString() !== 'NaN') ) {
                return arg;
            }
        }
        return null;
    }
    
    函数合并(){
    变量i,未定义,arg;
    对于(i=0;i
    对于那些希望代码尽可能短,并且不介意有点不够清晰的人,您也可以按照@impinball的建议使用此代码。这利用了NaN永远不等于NaN的事实。您可以在此处阅读更多关于此的内容:

    函数合并(){
    变量i,arg;
    对于(i=0;i
    是的,很快就会到来。请参阅和

    看起来是这样的:

    var myEmptyValue = 1;
    myEmptyValue = null;
    if ( myEmptyValue === null ) { window.alert('it is null'); }
    // alerts
    
    if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
    // alerts
    
    x ?? y
    
    例子
    请注意,React的
    create React app
    工具链支持空合并,因为。在发行说明中:

    可选的链接和空合并运算符

    我们现在支持可选的链接和空合并操作符

    // Optional chaining
    a?.(); // undefined if `a` is null/undefined
    b?.c; // undefined if `b` is null/undefined
    
    // Nullish coalescing
    undefined ?? 'some other default'; // result: 'some other default'
    null ?? 'some other default'; // result: 'some other default'
    '' ?? 'some other default'; // result: ''
    0 ?? 300; // result: 0
    false ?? true; // result: false
    

    这就是说,如果您使用
    create react app
    3.3.0+,您可以开始在您的react app中使用null coalesce操作符。

    它有望很快在Javascript中提供,因为它从2020年4月起处于建议阶段。您可以监控此处的状态,以获得兼容性和支持-

    对于使用Typescript的用户,可以使用

    从文件中-

    您可以将此功能--
    ??
    操作符--视为“坠落”的一种方式 返回“在处理
    null
    未定义时返回默认值
    像这样编写代码

    让x=foo??bar();

    这是一种新的方式,表示值
    foo
    将在“存在”时使用;但当值
    null
    未定义时使用,
    在原处计算
    bar()

    好的,回答正确 它是否存在于JavaScript中?是的,它存在。但是。它目前从2020-02-06年的at开始,并不是所有地方都支持它。请按照下面URL中的链接,转到“规范”和“浏览器兼容性”标题,以获取有关它所在位置的更多信息

    引自:

    空c
    let x = ["foo"]
    let y = { foo: "fizz" }
    
    x[0] ??= "bar"  // "foo"
    x[1] ??= "bar"  // "bar"
    
    y.foo ??= "buzz"  // "fizz"
    y.bar ??= "buzz"  // "buzz"
    
    x  // Array [ "foo", "bar" ]
    y  // Object { foo: "fizz", bar: "buzz" }
    
    body.head.eyes[0]  //body, head, eyes  may be null 
    
    (((body||{}) .head||{}) .eyes||[])[0] ||'left eye'