Number:数字类型,包括整数和浮点数,例如:42,3.14159。
String:字符串类型,用于表示文本数据,例如:“Hello, World!”。
Boolean:布尔类型,有两个值:true(真)和 false(假)。
Object:对象类型,用于存储键值对的集合。
Null:有一个值null,表示一个空值或者无值。
Undefined:有一个值undefined,表示未定义或不存在的值。
Symbol:符号类型,是一种新的数据类型(ES6引入),用于创建匿名的对象属性。
BigInt:大整数类型,用于存储任意精度的整数。
如何判断
let number = 123;
console.log(typeof number); // 输出 "number"
let string = "Hello";
console.log(typeof string); // 输出 "string"
let boolean = true;
console.log(typeof boolean); // 输出 "boolean"
let object = {};
console.log(typeof object); // 输出 "object"
let array = [];
console.log(typeof array); // 输出 "object"
let nullValue = null;
console.log(typeof nullValue); // 输出 "object"
let undefinedValue = undefined;
console.log(typeof undefinedValue); // 输出 "undefined"
let functionValue = function() {};
console.log(typeof functionValue); // 输出 "function"
注意,typeof对于数组和null会返回"object"。如果你需要更准确地检测这些类型,可以使用Array.isArray()来检测数组,使用value === null来检测null。
let array = [];
console.log(Array.isArray(array)); // 输出 true
let nullValue = null;
console.log(nullValue === null); // 输出 true
使用 instanceof 操作符:这个操作符用于判断一个对象是否是一个类的实例。但是,它不能用于判断基本数据类型。
let array = [];
console.log(array instanceof Array); // 输出 true
let date = new Date();
console.log(date instanceof Date); // 输出 true
使用 Object.prototype.toString.call() 方法:这个方法可以准确判断所有的数据类型
let number = 123;
console.log(Object.prototype.toString.call(number)); // 输出 "[object Number]"
let string = "Hello";
console.log(Object.prototype.toString.call(string)); // 输出 "[object String]"
let boolean = true;
console.log(Object.prototype.toString.call(boolean)); // 输出 "[object Boolean]"
let object = {};
console.log(Object.prototype.toString.call(object)); // 输出 "[object Object]"
let array = [];
console.log(Object.prototype.toString.call(array)); // 输出 "[object Array]"
let nullValue = null;
console.log(Object.prototype.toString.call(nullValue)); // 输出 "[object Null]"
let undefinedValue = undefined;
console.log(Object.prototype.toString.call(undefinedValue)); // 输出 "[object Undefined]"
let functionValue = function() {};
console.log(Object.prototype.toString.call(functionValue)); // 输出 "[object Function]"
你可以使用typeof操作符来判断一个值是否为BigInt类型。以下是一个例子
let bigintValue = BigInt(123);
console.log(typeof bigintValue); // 输出 "bigint"
let numberValue = 123;
console.log(typeof numberValue); // 输出 "number"