JS红宝书之第三章(三)数据类型(一)

数据类型

  • 基本数据类型
    • 数字 number
      • 正数、浮点数、NaN
    • 字符串 string
      • 所有用单引号、双引号、反引号(模板字符串)包起来的都是字符串
    • 布尔 boolean:true、false
    • 空对象 null
    • 未定义 undefined
    • 符号 Symbol
  • 引用数据类型
    • 对象数据类型 object
      • {} 普通对象

      • [] 数组对象

      • /^$/ 正则对象

        验证是否为有效数字:/^[+-]?(\d|([1-9]\d+))(.\d+)?$/
        + Math 数学函数对象
        + Date 日期对象

    • 函数数据类型 function

typeof 操作符

基于 typeof 检测出来的结果:首先是一个字符串,并且字符串中包含对应的类型

  • 局限性
    1. typeof null => "object" 但 null 并不是对象
    2. typeof 无法细分出当前值是普通对象还是数组对象,因为只要是对象,返回的结果都是字符串 "object"
  • typeof 只能检验 数字 、字符串 、 undefined 、 布尔
  typeof 1; // "number"
  typeof NaN; // "number"
  typeof 'str'; // "string"
  typeof true; // "boolean"
  typeof null; // "object" 局限性之一
  typeof undefined; // "undefined"
  var a;
  // var b;
  typeof a; // undefined 声明变量但未初始化
  typeof b; // undefined 未声明;对于尚未声明的变量,只能进行 typeof 操作,其他操作都会报错
  typeof {}; // "object"
  typeof []; // "object"
  typeof /^$/; // "object"
  typeof Math; // "object"
  typeof function(){}; // "function"
  typeof Date; // "function"
检测数据类型方式
  1. typeof [val]: 用来检测数据类型的运算符
  2. instanceof: 用来检测当前实例是否隶属于某各类
  3. constructor: 基于构造函数检测数据类型(基于类的方式)
  4. Object.prototype.toString().call(): 检测数据类型最好

面试题

  typeof typeof typeof []; // "string",先算离[]最近的typeof
  1. typeof [] => "object"
  2. typeof "object" => "string"
  3. 因为 typeof 检测出来的结果是字符串,只要出现两个及两个以上检测,结果就是 "string"

instanceof

语法:result = variable instanceof constructor

  • 检测引用数据类型
var obj = {};
obj instanceof Object; // true

var arr = [];
arr instanceof Array; // true

var pattern = /[1-9]/g;
pattern instanceof RegExp; // true

var fn = function(){};
fn instanceof Function; // true

Undefined 与 Null

var a ;
console.log('a的类型: ' + typeof a); // undefined 表示 a 未定义
console.log('从未声明过的 b 类型: ' + typeof b); // undefined 表示 b 未曾声明
console.log(a); // => undefined
console.log(b); // => error:Uncaught ReferenceError: b is not defined at xxx.html:36

// 声明为 null 的变量准备在将来保存对象
// null 表示一个空指针对象
console.log('typeof null => ', typeof null); // object
// undefined 派生自 null ????
console.log('undefined == null ==>', undefined == null);

Boolean()

false 值只有五种 false '' 0 NaN undefined null

!! 是运算符中的 Boolean()

  • 在项目中可应用于对 一个变量为 空字符串 或者为 undefined 或者为 null 的排除
// Boolean 有两个值 true false
// String
console.log('Boolean(\' \') => ', Boolean(' ')); // true
console.log('Boolean(\'\') => ', Boolean('')); // false 1

// Number
console.log('Boolean(0) => ', Boolean(0)); // false 2
console.log('Boolean(NaN) => ', Boolean(NaN)); // false 3
console.log('Boolean(123) => ', Boolean(123)); // true

// Object
console.log('Boolean(null) => ', Boolean(null)); // false 4
console.log('Boolean({}) => ', Boolean({})); // true
console.log('Boolean([]) => ', Boolean([])); // true

// function
console.log('function(){} => ', Boolean(function(){})); // true

// Undefined
console.log('Boolean(undefined) => ', Boolean(undefined)); // false 5

你可能感兴趣的:(JS红宝书之第三章(三)数据类型(一))