#Js篇:基本数据类型(7)Null、Undefined、Boolean、String、Number、Symbol、Bigint&引用数据类型&类型判断方法

发布时间:2024年01月23日

七种基本数据类型:

  1. 布尔值(Boolean),有 2 个值分别是:true 和 false。
  2. null,一个表明 null 值的特殊关键字。JavaScript 是大小写敏感的,因此 null 与 Null、NULL或变体完全不同。
  3. undefined,和 null 一样是一个特殊的关键字,undefined 表示变量未赋值时的属性。
  4. 数字(Number),整数或浮点数,例如: 42 或者3.14159。
  5. 任意精度的整数(BigInt),可以安全地存储和操作大整数,甚至可以超过数字的安全整数限制。
  6. 字符串(String),字符串是一串表示文本值的字符序列,例如:“Howdy”。
  7. 代表(Symbol,在 ECMAScript 6 中新添加的类型)。一种实例是唯一且不可改变的数据类型。

应用类型

以及对象(Object)

判断方法

typeof:
typeof true; // "boolean"
typeof null; // "object" (历史遗留问题,实际应为“null”)
typeof undefined; // "undefined"
typeof 42; // "number"
typeof BigInt(9007199254740991); // "bigint"
typeof BigInt(1n) === 'bigint'; // true
typeof "Howdy"; // "string"
let sym = Symbol("description");
typeof sym; // 返回 "symbol"
Object.prototype.toString.call()

可以更准确地判断包括 null 和数组、函数等在内的复杂类型

Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(42); // "[object Number]"
Object.prototype.toString.call(BigInt(9007199254740991)); // "[object BigInt]"
Object.prototype.toString.call("Howdy"); // "[object String]"
Object.prototype.toString.call({}) === '[object Object]';
Object.prototype.toString.call([]) === '[object Array]';
Object.prototype.toString.call(new Date()) === '[object Date]';
instanceof:—引用类型判断

判断一个对象是否是某个构造函数的实例,对于引用类型非常有用,但对基本类型(如布尔值、数字、字符串、null、undefined 和 BigInt)无效。

// 对于引用类型
let arr = [];
arr instanceof Array; // true
使用 Array.isArray() 判断是否为数组:
Array.isArray([]); // true
// or
Object.prototype.toString.call([]) === '[object Array]';
文章来源:https://blog.csdn.net/weixin_47075554/article/details/135764959
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。