zoukankan      html  css  js  c++  java
  • JavaScript null 和 undefined 的比较 Better

    null

        定义:

            表示“空”的对象(空值),转为数值时为0。

    Number(null) // 0
    5 + null // 5

        用法:

            调用函数时,某个参数未设置任何值,这时就可以传入null,表示该参数为空。

            比如,某个函数接受引擎抛出的错误作为参数,如果运行过程中未出错,那么这个参数就会传入null,表示未发生错误。

    undefined

        定义:

            表示“此处无定义”的原始值(未定义),转为数值时为 NaN

    Number(undefined) // NaN
    5 + undefined // NaN

        用法:

    // 变量声明了,但没有赋值
    var i;
    i // undefined
    
    // 调用函数时,应该提供的参数没有提供,该参数等于 undefined
    function f(x) {
      return x;
    }
    f() // undefined
    
    // 对象没有赋值的属性
    var  o = new Object();
    o.p // undefined
    
    // 函数没有返回值时,默认返回 undefined
    function f() {}
    f() // undefined

    补充

        在if语句中,它们都会被自动转为false,相等运算符(==)甚至直接报告两者相等。

    if (!undefined) {
      console.log('undefined is false');
    }
    // undefined is false
    
    if (!null) {
      console.log('null is false');
    }
    // null is false
    
    undefined == null
    // true
  • 相关阅读:
    MVC 后台DataTable 前台遍历
    oracle 创建表空间详细介绍
    C# Chart 折线图 多条数据展示
    ASP.NET Request.QueryString 出现乱码问题
    生成XML文件
    什么是Intent(意图)
    HTTP错误405-Method Not Allowed
    通过剪切板传递数据—— 传递一个对象
    Linux下crontab命令的用法
    Redis使用介绍
  • 原文地址:https://www.cnblogs.com/huangtq/p/14426432.html
Copyright © 2011-2022 走看看