GVKun编程网logo

javascript中是否存在null-coalescing(Elvis)运算符或安全导航运算符?(js 是否存在)

10

本文将分享javascript中是否存在null-coalescing的详细内容,并且还将对Elvis运算符或安全导航运算符?进行详尽解释,此外,我们还将为大家带来关于c#–使用null-coales

本文将分享javascript中是否存在null-coalescing的详细内容,并且还将对Elvis运算符或安全导航运算符?进行详尽解释,此外,我们还将为大家带来关于c# – 使用null-coalescing运算符进行隐式转换、javascript 中 && 运算符和 || 运算符的使用、JavaScript 中是否有“空值合并”运算符?、JavaScript 中是否有用于检查对象属性的“not in”运算符?的相关知识,希望对你有所帮助。

本文目录一览:

javascript中是否存在null-coalescing(Elvis)运算符或安全导航运算符?(js 是否存在)

javascript中是否存在null-coalescing(Elvis)运算符或安全导航运算符?(js 是否存在)

我将举例说明:

猫王算子(?:)


Elvis运算符”是Java三元运算符的缩写。一个方便的例子是,如果表达式解析为false或null,则返回“明智的默认值”。一个简单的示例可能如下所示:

def gender = user.male ? "male" : "female"  //traditional ternary operator usagedef displayName = user.name ?: "Anonymous"  //more compact Elvis operator

安全导航操作员(?。)

安全导航运算符用于避免NullPointerException。通常,当您拥有对对象的引用时,可能需要在访问对象的方法或属性之前验证其是否为null。为了避免这种情况,安全的导航运算符将只返回null而不是引发异常,例如:

def user = User.find( "admin" )           //this might be null if ''admin'' does not existdef streetName = user?.address?.street    //streetName will be null if user or user.address is null - no NPE thrown

答案1

小编典典

您可以使用逻辑“ OR”运算符代替Elvis运算符:

例如displayname = user.name || "Anonymous"

但是Javascript当前没有其他功能。如果您需要其他语法,建议您查看CoffeeScript。它具有一些速记,与您要查找的类似。

例如存在运算符

zip = lottery.drawWinner?().address?.zipcode

功能快捷键

()->  // equivalent to function(){}

性感函数调用

func ''arg1'',''arg2'' // equivalent to func(''arg1'',''arg2'')

还有多行注释和类。显然,您必须将其编译为javascript或插入到页面中,<scripttype=''text/coffeescript>''但这会增加很多功能:)。使用<scripttype=''text/coffeescript''>实际上仅用于开发而非生产。

c# – 使用null-coalescing运算符进行隐式转换

c# – 使用null-coalescing运算符进行隐式转换

我发现了我的程序的一个奇怪的行为,经过进一步的分析,我发现在我的C#知识或其他地方可能存在错误.我相信这是我的错,但我无法在任何地方找到答案……
public class B
{
    public static implicit operator B(A values) 
    {
        return null; 
    }
}
public class A { }

public class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = a ?? new B();
        //b = null ... is it wrong that I expect b to be B() ?
    }
}

此代码中的变量“b”被计算为null.我不明白为什么它是null.

我用Google搜索并在此问题中找到了回复 – Implicit casting of Null-Coalescing operator result – 与官方规范.

但是按照这个规范,我找不到“b”为空的原因:(也许我读错了,在这种情况下我为垃圾邮件道歉.

If A exists and is not a nullable type or a reference type,a compile-time error occurs.

……事实并非如此.

If b is a dynamic expression,the result type is dynamic. At run-time,a is first evaluated. If a is not null,a is converted to dynamic,and this becomes the result. Otherwise,b is evaluated,and this becomes the result.

……事实并非如此.

Otherwise,if A exists and is a nullable type and an implicit conversion exists from b to A0,the result type is A0. At run-time,a is unwrapped to type A0,b is evaluated and converted to type A0,and this becomes the result.

…存在,从b到A0的隐式转换不存在.

Otherwise,if A exists and an implicit conversion exists from b to A,the result type is A. At run-time,a becomes the result. Otherwise,b is evaluated and converted to type A,从b到A的隐式转换不存在.

Otherwise,if b has a type B and an implicit conversion exists from a to B,the result type is B. At run-time,a is unwrapped to type A0 (if A exists and is nullable) and converted to type B,b is evaluated and becomes the result.

… b有一个B型,从a到B存在隐式转换.
a被评估为null.因此,应评估b,结果应为b.

Otherwise,a and b are incompatible,and a compile-time error occurs.
Does not happen

我错过了什么吗?

解决方法

嗯,规范说(我改为x和y,以减少混淆):

• Otherwise,if y has a type Y and an implicit conversion exists from x to Y,the result type is Y. At run-time,x is first evaluated. If x is not null,x is unwrapped to type X0 (if X exists and is nullable) and converted to type Y,y is evaluated and becomes the result.

有时候是这样的.首先,检查左侧x(仅为a)为空.但它本身并不是空的.然后使用左侧.然后运行隐式转换.它的类型B的结果是…… null.

请注意,这与以下内容不同:

A a = new A();
    B b = (B)a ?? new B();

在这种情况下,左操作数是表达式(x),其本身为空,结果变为右侧(y).

也许引用类型之间的隐式转换应该返回null(if和)仅当原始为null时,作为一种好的做法?

我想那些编写规范的人可能会这样做(但没有):

• Otherwise,x is first evaluated and converted to type Y. If the output of that conversion is not null,that output becomes the result. Otherwise,y is evaluated and becomes the result.

也许那会更直观?无论转换的输入是否为null,它都会强制运行时调用隐式转换.如果典型的实现快速确定null→null,那应该不会太昂贵.

javascript 中 && 运算符和 || 运算符的使用

javascript 中 && 运算符和 || 运算符的使用

前言

在前端开发领域中,&& 运算符和 || 运算符是使用率和频繁度比较高的,&& 运算符和 || 运算符的功能特别强大,想成为一名优秀的前端工程师,&& 运算符和 || 运算符是必不可少的,但是很多前端工程师 (刚入门的小白【包括小编本身】) 对于 && 运算符和 || 运算符的使用率极为低下,之前小编在学校开发一些项目的时候根本就没有用到过,因为我们已经被传统概念束缚了。我们对于 && 运算符和 || 运算符的理解是这样的

&& 运算符

  • && 运算符左边的结果和右边的结果同时为真时,结果真

  • && 运算符左边的结果和右边的结果同时为假时,结果为假

  • && 运算符左边的结果和右边的结果有一个为假时,结果为假  

总结:同真为真,否则为假

|| 运算符

  • || 运算符左边的结果和右边的结果同时为真,结果为真

  • || 运算符左边的结果和右边的结果有一个为假时,结果为真

  • || 运算符左边的结果和右边的结果同时为假时,结果为假

总结:同假为假,否则为真

但是实际上真的是这样吗?我们看下关于 && 运算符的小 demo

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <script type="text/javascript">
            let result=1&&2;
            console.log(result);
            
            
        </script>
    </body>
</html>

你想的结果是不是返回 true 呀!小编一开始也是和你们一样,但是在学习中实践了一下,并非这样,这里请允许小编打个小广告,各位同行可以在腾讯课堂 bilibili 搜索渡一教育,良心推荐,说实在里面的老师讲课讲的非常优秀,有兴趣的同行可以去尝试一下,扯远了,我们回归正题,实际上返回的结果是 2。

|| 运算符的小 demo

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <script type="text/javascript">
            var result=1||0
            console.log(result);
        </script>
    </body>
</html>

结果:

是不是很惊讶!,天哪!出乎我的意料,两次的结果返回值都不是 true 或者 false,好了小编也不和你们卖关子了。直接进入正题。

本章目标

  • 学会使用 && 运算符和 || 运算符

  • 通过案例加强对 && 运算符和 || 运算符的理解

案例实践 (通过加载 json 渲染数据)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <stle type="text/css">
            #myTab{
                width: 800px;
                margin: 0 auto;
            }
            
            
        </style>
    </head>
    <body>
        <table border="1" cellspacing="0" cellpadding="0" id="myTab">
            <tr>
                <th>编号</th>
                <th>名称</th>
                <th>价格</th>
                <th>状态</th>
            </tr>
            
        </table>
        <script src="../js/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            //0代表待支付,1代表已支付,2代表已收货,3代表其它
            var  orderArray=[
            {
                id:10001,
                name:''小米9'',
                price:1999,
                status:0,
            },
            {
                id:10002,
                name:''huaweiPro'',
                price:2999,
                status:1,
            },
            {
                id:10003,
                name:''小米8'',
                price:999,
                status:2,
            },
            {
                id:10004,
                name:''荣耀8X'',
                price:1399,
                status:3,
            }
            ];
            $("#myTab tr:not(:eq(0))").remove();
            for(var i=0;i<orderArray.length;i++){
                var tr=$("<tr/>");
                var td1=$("<td/>");
                var td2=$("<td/>");
                var td3=$("<td/>");
                var td4=$("<td/>")
                td1.html(orderArray[i].id);
                td2.html(orderArray[i].name);
                td3.html(orderArray[i].price);
                if(orderArray[i].status==0){
                    td4.html("待支付")
                }else if(orderArray[i].status==1){
                    td4.html("已支付")
                }else if(orderArray[i].status==2){
                    td4.html("已收货");
                }else if(orderArray[i].status==3){
                    td4.html("其它")
                }
                tr.append(td1);
                tr.append(td2);
                tr.append(td3);
                tr.append(td4);
                $("#myTab").append(tr);
            }
        </script>
    </body>
</html>

效果图如下:

这是我们没有使用 && 运算符和 || 运算符的结果,接下来我们使用 && 运算符和 || 运算符来简化 if...else..if...else 语句

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #myTab{
                width: 800px;
                margin: 0 auto;
            }
        </style>
    </head>
    <body>
        <table border="1" cellspacing="0" cellpadding="0" id="myTab">
            <tr>
                <th>编号</th>
                <th>名称</th>
                <th>价格</th>
                <th>状态</th>
            </tr>
        </table>
        <script src="../js/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            //0代表待支付,1代表已支付,2代表已收货,3代表其它
            var  orderArray=[
            {
                id:10001,
                name:''小米9'',
                price:1999,
                status:0,
            },
            {
                id:10002,
                name:''huaweiPro'',
                price:2999,
                status:1,
            },
            {
                id:10003,
                name:''小米8'',
                price:999,
                status:2,
            },
            {
                id:10004,
                name:''荣耀8X'',
                price:1399,
                status:3,
            }
            ];
            $("#myTab tr:not(:eq(0))").remove();
            for(var i=0;i<orderArray.length;i++){
                var tr=$("<tr/>");
                var td1=$("<td/>");
                var td2=$("<td/>");
                var td3=$("<td/>");
                var td4=$("<td/>")
                td1.html(orderArray[i].id);
                td2.html(orderArray[i].name);
                td3.html(orderArray[i].price);
                var status=orderArray[i].status== 0 && "待支付" ||orderArray[i].status== 1 && "已支付" ||orderArray[i].status== 2 && "已收货" ||orderArray[i].status== 3 && "其它"
                td4.html(status); 
//                if(orderArray[i].status==0){
//                    td4.html("待支付")
//                }else if(orderArray[i].status==1){
//                    td4.html("已支付")
//                }else if(orderArray[i].status==2){
//                    td4.html("已收货");
//                }else{
//                    td4.html("其它")
//                }
                tr.append(td1);
                tr.append(td2);
                tr.append(td3);
                tr.append(td4);
                $("#myTab").append(tr);
            }
        </script>
    </body>
</html>

 

在这里我们用一句代码解决了 if..else..if..else 的代码操作,使用了 && 运算符和 || 运算符代替使代码更加简洁方便,当然 && 运算符和 || 运算符的使用不仅仅是这样,总之 && 运算符和 || 运算符的功能特别强大,我们要学会使用

结尾

&& 运算符

  • 先看第一个表达式转换为布尔值的结果,如果为真,那么它会看第二个表达式转换为布尔值的结果,然后如果只有两个表达式的话,只看第二个表达式的结果就可以返回该表达式的值

  • 当第一个表达式的值为 false 时,直接返回第一个表达式的值,不再往后看

  • 如果第一个操作数是对象,则返回第二个操作数

  • 如果两个操作数都是对象,则返回第二个操作数

  • 如果第二个操作数是对象,则只有在第一个操作数的求值结果为 true 的情况才会返回该对象

  • 如果一个操作数为 null, 则返回 null

  • 如果第一个操作数是 NaN, 则返回 NaN

  • 如果第一个操作数是 undefined, 则返回 undefined

|| 运算符

  • 先看第一个表达式转换为布尔值的结果,如果为假,那么它会看第二个表达式转换为布尔值的结果,然后如果只有两个表达式的话,只看第二个表达式的结果就可以返回该表达式的值

  • 当第一个表达式的值为 false 时,直接返回第二个表达式的值,不再往后看

  • 如果第一个操作数是对象,则返回第一个第一个操作数

  • 如果第一个操作数的求值结果为 false, 则返回第二个操作数

  • 如果两个操作数都是对象,则返回第一个操作数

  • 如果两个操作数都是 null, 则返回 null

  • 如果两个操作数都是 NaN,则返回 NaN

  • 如果两个操作数都是 undefined,则返回 undefined

被认定为 false 的值:false""NaNnullundefined

原文出处:https://www.cnblogs.com/jjgw/p/11109685.html

JavaScript 中是否有“空值合并”运算符?

JavaScript 中是否有“空值合并”运算符?

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

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

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

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

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

恕我直言,这有点恶心。我能做得更好吗?

答案1

小编典典

更新

JavaScript 现在支持空值合并运算符 (??)。当其左侧操作数为nullor时返回其右侧操作数undefined,否则返回其左侧操作数。

旧答案

请在使用前检查兼容性。


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

var whatIWant = someString || "Cookies!";

在某些情况下(下文说明)该行为与 C# 的行为不匹配,但这是在 JavaScript 中分配默认/替代值的一般、简洁的方式。


澄清

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

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

这意味着:

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

JavaScript 中是否有用于检查对象属性的“not in”运算符?

JavaScript 中是否有用于检查对象属性的“not in”运算符?

JavaScript中是否有任何类型的“不在”运算符来检查对象中是否不存在属性?我无法在 Google 或 Stack Overflow
上找到任何相关信息。这是我在需要这种功能的地方工作的一小段代码:

var tutorTimes = {};$(checked).each(function(idx){  id = $(this).attr(''class'');  if(id in tutorTimes){}  else{    //Rest of my logic will go here  }});

如您所见,我会将所有内容都放入else声明中。在我看来,仅仅为了使用该部分而设置一个声明是错误if的。else``else

答案1

小编典典

设置 if/else 语句只是为了使用 else 部分对我来说似乎是错误的......

只要否定你的条件,你就会得到else里面的逻辑if

if (!(id in tutorTimes)) { ... }

关于javascript中是否存在null-coalescingElvis运算符或安全导航运算符?的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于c# – 使用null-coalescing运算符进行隐式转换、javascript 中 && 运算符和 || 运算符的使用、JavaScript 中是否有“空值合并”运算符?、JavaScript 中是否有用于检查对象属性的“not in”运算符?等相关内容,可以在本站寻找。

本文标签: