WebGL Tutorial
and more

基本数据类型

撰写时间:2024-02-11

修订时间:2024-11-26

概述

JavaScript的基本数据类型有:

  • Undefined
  • Null
  • Boolean
  • String
  • Symbol
  • Number
  • BigInt
  • Object

共8种。

可使用typeof操作符来判断各种数据类型。

function checkType(data) { if (typeof data === 'object' && Array.isArray(data)) { console.log('array'); } else { console.log(typeof data); } } checkType("Hello"); // string checkType(true); // boolean checkType(12); // number checkType(0.87); // number checkType([1, 2, 3]); // array checkType({ name: 'Mike', age: 35 // object });

typeof返回值是相应数据类型的小写字母的字符串。另外,数组与Object的类型一样,因此需进一步使用Array.isArray静态方法来进一步判断是否数组。

但如果将Uint8ArrayTypedArray加进来,则typeof所返回的结果为object,因此上面的方法不足以应对这种情况。

使用constructor属性值可以。

[ 'str', // String true, // Boolean 23, // Number 0.75, // Number [1, 2, 3], // Array {name: 'Mike'}, // Object new Uint8Array(10), // Uint8Array new Float32Array(10) // Float32Array ].forEach(item => { console.log(item.constructor); });

item.constructor的类型是object,因此可使用下面的代码来进行判断:

let data = new Uint8Array(10); console.log(data.constructor === Uint8Array); // true

Undefined 类型

Undefined类型只有一个值为undefined。未被赋值的变量,其值为undefined

let a; console.log(a); // undefined console.log(typeof a); // undefined

Null 类型

Null类型只有一个值为null

在支持指针的编程语言中,null值通常指某个指针指向了不存在或无效的对象或地址,也称为空指针。

let a = {}; // refers to an object a = null; // breaks the reference console.log(a); // null console.log(typeof a); // object

Boolean 类型

Boolean类型代表逻辑结果,其值分为truefalse

String 类型

Symbol 类型

Number 类型

Number类型,其值包括整数与浮点数,以及一个称为NaN(Not a number)的数值。

let a = 5; console.log(typeof a); // number let b = 23.5; console.log(typeof b); // number

BigInt 类型

BigInt类型代表一个整数的数据类型。该类型的值可为任意大小,且没有特定字长的限制。

Object 类型

详见Object

参考资源

  1. ECMA 262: ECMAScript Language Types
  2. 4 Ways to Create an Enum in JavaScript