在JavaScript中,可以使用typeof
操作符来查看变量的类型。typeof
操作符返回一个表示操作数类型的字符串。下面是一些示例代码,展示了如何使用typeof
来查看不同类型的变量:
let num = 123;
console.log(typeof num); // 输出 "number"
let str = "Hello, world!";
console.log(typeof str); // 输出 "string"
let bool = true;
console.log(typeof bool); // 输出 "boolean"
let obj = { key: "value" };
console.log(typeof obj); // 输出 "object"
let arr = [1, 2, 3];
console.log(typeof arr); // 输出 "object",注意数组也是对象
let func = function() {};
console.log(typeof func); // 输出 "function"
let und;
console.log(typeof und); // 输出 "undefined"
let nul = null;
console.log(typeof nul); // 输出 "object",这是一个历史悠久的JavaScript bug
let symbol = Symbol("sym");
console.log(typeof symbol); // 输出 "symbol"
let bigint = 123n;
console.log(typeof bigint); // 输出 "bigint"
需要注意的是,typeof
对于null
值会返回"object"
,这实际上是JavaScript中的一个错误,但由于兼容性原因,一直没有被修复。
此外,对于更复杂的对象类型检查,可以使用instanceof
操作符或者Object.prototype.toString.call()
方法。例如:
let date = new Date();
console.log(date instanceof Date); // 输出 true
console.log(Object.prototype.toString.call(date) === '[object Date]'); // 输出 true
let regex = /regex/;
console.log(regex instanceof RegExp); // 输出 true
console.log(Object.prototype.toString.call(regex) === '[object RegExp]'); // 输出 true
instanceof
操作符用于检测构造函数的prototype
属性是否出现在某个实例对象的原型链上。而Object.prototype.toString.call()
方法则可以更准确地检测对象的内部[[Class]]
属性,从而判断对象的类型。
高校公开课
618音视频通信直播系列
Tencent Serverless Hours 第13期
腾讯云存储知识小课堂
云+社区沙龙online [国产数据库]
腾讯云湖存储专题直播
第136届广交会企业系列专题培训
云+社区沙龙online第5期[架构演进]
企业创新在线学堂
领取专属 10元无门槛券
手把手带您无忧上云