返回
JS-typeof与数据类型转换
前端
2023-11-28 14:23:16
一、检测数据类型(typeof)
1. 简介
JavaScript 中的 typeof 运算符用于检测数据的类型,结果为一个字符串,表示数据所对应的类型。typeof 既可以作为运算符,也可以作为函数使用,语法如下:
console.log(typeof(age)/ console.log(typeof age)
2. 基本类型检测
typeof 运算符可以检测以下基本数据类型:
- 字符串("string")
- 数字("number")
- 布尔值("boolean")
- undefined("undefined")
- null("object")
3. 复杂类型检测
typeof 运算符也可以检测以下复杂数据类型:
- 对象("object")
- 函数("function")
- 数组("object")
- 日期("object")
- 正则表达式("object")
二、数据类型转换
在 JavaScript 中,您可以使用数据类型转换函数将一种数据类型转换为另一种数据类型。最常用的数据类型转换函数包括:
1. Number()
Number() 函数将值转换为数字。如果值不能转换为数字,则返回 NaN(Not a Number)。
2. String()
String() 函数将值转换为字符串。
3. Boolean()
Boolean() 函数将值转换为布尔值。如果值是 true 或 "true",则返回 true;否则,返回 false。
三、严格模式下的 typeof 行为
在严格模式下,typeof 运算符的行为略有不同。例如,在非严格模式下,null 的 typeof 为 "object",而在严格模式下,null 的 typeof 为 "null"。
四、示例和代码片段
以下是一些示例和代码片段,展示了如何使用 typeof 运算符检测数据类型,以及如何使用数据类型转换函数转换数据类型:
// 检测数据类型
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"
// 数据类型转换
var num = Number("123");
console.log(typeof num); // "number"
var str = String(123);
console.log(typeof str); // "string"
var bool = Boolean(0);
console.log(typeof bool); // "boolean"