Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 数据类型判断

作者:仯孒①個亾哋杺¢涳孒   发布日期:2026-05-30   浏览:85

// js 数据类型判断

// 使用 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" - 注意:typeof null 返回 "object",这是一个历史遗留问题
console.log(typeof {}); // "object" - 判断对象类型
console.log(typeof []); // "object" - 数组也被认为是对象
console.log(typeof function() {}); // "function" - 判断函数类型

// 使用 instanceof 操作符
let arr = [];
console.log(arr instanceof Array); // true - 判断是否为数组实例

// 使用 constructor 属性
console.log((42).constructor === Number); // true - 判断是否为数字构造函数的实例
console.log(('hello').constructor === String); // true - 判断是否为字符串构造函数的实例
console.log((true).constructor === Boolean); // true - 判断是否为布尔构造函数的实例
console.log(([]).constructor === Array); // true - 判断是否为数组构造函数的实例
console.log(({}).constructor === Object); // true - 判断是否为对象构造函数的实例

// 使用 Array.isArray 方法
console.log(Array.isArray([])); // true - 更可靠的数组判断方法
console.log(Array.isArray({})); // false - 不是数组

以上代码展示了多种在 JavaScript 中判断数据类型的方法。typeof 是最常用的方式,但对 null 和数组的判断可能会有误导。instanceofconstructor 可以用于更具体的类型判断,而 Array.isArray 是判断数组的推荐方法。

上一篇:js dataset

下一篇:js 查看数据类型

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站