JavaScript 的数据类型【一】(null,undefined,boolean)

JavaScript 语言的每一个值,都属于某一种数据类型。JavaScript 的数据类型,共有七种。数值字符串布尔值这三种是原始类型。对象则称为合成类型。undefinednull,为两个特殊值。ES6 添加了Symbol类型的值。

一.概念

1.类型介绍

  1. 数值(number):整数和小数(比如13.14
  2. 字符串(string):文本(比如Hello World
  3. 布尔值(boolean):表示真伪的两个特殊值,即true(真)和false(假)
  4. undefined:表示“未定义”或不存在,即由于目前没有定义,所以此处暂时没有任何值
  5. null:表示空值,即此处的值为空
  6. 对象(object):各种值组成的集合
    • 狭义的对象(object)
    • 数组(array)
    • 函数(function)

2.typeof 运算符

  1. 确定值类型有三种方式:
    typeof运算符;②instanceof运算符;③Object.prototype.toString方法
  2. 使用typeof运算符打印数值类型:
    数值打印number;②字符串打印string;③布尔值打印boolean;④函数打印function;⑤undefined打印undefined;⑥对象打印object(由于历史原因 null也打印object);
    //①
    typeof 123 // "number"
    //②
    typeof '123' // "string"
    //③
    typeof false // "boolean"
    //④
    function f() {}
    typeof f  // "function"
    //⑤
    typeof undefined // "undefined"
    
    // ReferenceError: v is not defined
    typeof v// "undefined"
    
    //⑥
    typeof window // "object"
    typeof {} // "object"
    typeof [] // "object"
    typeof null // "object"
    

二. null, undefined 和布尔值

1.null 和 undefined

Ⅰ.异同点

  1. undefined代表未定义;null代表空,语法效果没有什么区别;

  2. 相同点:①给变量赋值undefined或者null,几乎是等价的;②在if语句中都会转成false;③相等运算符==报告两者相等

  3. 不同点:①null使用Number转换为0;②undefined使用Number转换为NaN;

  4. 验证上述范例:

    //①
    var a = undefined;
    // 基本等价
    var a = null;
    
    //②
    if (!undefined) {
      console.log('undefined is false');
    }
    // undefined is false
    
    if (!null) {
      console.log('null is false');
    }
    // null is false
    
    console.log(undefined == null)
    // true
    
    //③
    console.log(Number(null)) // 0
    console.log(Number(undefined))// NaN
    

Ⅱ.使用场景

  1. null使用场景:在调用函数时,没有值的时候,可传入null表示无值;

  2. undefined表示未定义:典型场景,①变量声明,但没有赋值;②调用函数时,应该提供的参数没有提供,该参数等于 undefined;③对象没有赋值的属性;④ 函数没有返回值时,默认返回 undefined

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

2.布尔值

Ⅰ.返回boolean的逻辑运算符

  • 真为true和假为false
  • 返回boolean的逻辑运算符
    1. 前置逻辑运算符: !
    2. 相等运算符:===!====!=
    3. 比较运算符:>>=<<=

Ⅱ.boolean自动转换规则

  • 如下六个值undefinednullfalse0NaN""或’’(空字符串)自动转换为false;其余转换为true

  • 验证如上范例,空数组[],空对象{}都会自动转换为true

    if ('') {
    	console.log('true');
    }
    // 没有任何输出
    if ([]) {
    	console.log('true');
    }
    // true
    if ({}) {
    	console.log('true');
    }
    // true
    
发布了170 篇原创文章 · 获赞 61 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/NDKHBWH/article/details/103364348