zoukankan      html  css  js  c++  java
  • JS Undefined 类型

    JS Undefined 类型

    undefined 是 Undefined 类型的唯一值,它表示未定义的值。当声明变量未赋值时,或者定义属性未设置值时,默认值都为 undefined。

    示例1

    undefined 派生自 null,null 和 undefined 都表示空缺的值,转化为布尔值时都是假值,可以相等。

    console.log(null == undefined);  //返回 true
    

    null 和 undefined 属于两种不同类型,使用全等运算符(==)或 typeof 运算符可以进行检测。

    console.log(null === undefined);  //false
    console.log(typeof null);  //返回"object"
    console.log(typeof undefined);  //返回"undefined"
    

    示例2

    检测一个变量是否初始化,可以使用 undefined 快速检测。

    var a;//声明变量
    console.log(a);  //返回变量默认值为 undefined
    (a == undefined) && (a = 0);  //检测变量是否初始化,否则为其赋值
    console.log(a);  //返回初始值 0
    

    也可以使用 typeof 运算符检测变量的类型是否为 undefined。

    (typeof a == "undefined") && (a = 0);  //检测变量是否初始化,否则为其赋值
    

    示例3

    在下面代码中,声明了变量 a,但没有声明变量 b,然后使用 typeof 运算符检测它们的类型,返回的值都是字符串 "undefined"。说明不管是声明的变量,还是未声明的变量,都可以通过 typeof 运算符检测变量是否初始化。

    var a;
    console.log(typeof a);  //返回"undefined”
    console.log(typeof b);  //返回"undefined"
    

    对于未声明的变量 b 来说,如果直接在表达式中使用,会引发异常。

    console.log(b == undefined); //提75未定义的错误信息
    

    示例4

    对于函数来说,如果没有明确的返回值,则默认返回值也为

    function f(){}console.log(f());  //返回"undefined"
    

    undefined 隐含着意外的空值,而 null 隐含着意料之中的空值。因此,设置一个变量、参数为空值时,建议使用 null,而不是 undefined。

  • 相关阅读:
    Docker安装
    Mysql 安全登陆工具 mysql_config_editor
    位图索引对于DML操作的影响
    删除Oracle Online Redo 测试
    16 Managing Undo
    Linux 不杀进程的情况下,如何释放磁盘资源
    SFTP 服务搭建
    8. DBNEWID 工具(使用nid命令修改db name及dbid)
    Null 值对索引排序的影响案例一则
    opensshd 源码升级
  • 原文地址:https://www.cnblogs.com/kai-/p/12380174.html
Copyright © 2011-2022 走看看