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

js 查看数据类型

作者:城若幻影   发布日期:2025-10-30   浏览:77

// 使用 typeof 操作符查看基本数据类型
let str = "Hello, world!";
let num = 42;
let bool = true;
let und = undefined;
let nul = null;
let obj = { name: "Alice" };
let arr = [1, 2, 3];
let func = function() {};

console.log(typeof str); // "string"
console.log(typeof num); // "number"
console.log(typeof bool); // "boolean"
console.log(typeof und); // "undefined"
console.log(typeof nul); // "object" (这是一个历史遗留问题,null 实际上应该返回 "null")
console.log(typeof obj); // "object"
console.log(typeof arr); // "object" (数组在 JavaScript 中是对象)
console.log(typeof func); // "function"

// 使用 instanceof 操作符检查对象类型
console.log(arr instanceof Array); // true
console.log(obj instanceof Object); // true

// 使用 constructor 属性检查类型
console.log(str.constructor === String); // true
console.log(num.constructor === Number); // true
console.log(bool.constructor === Boolean); // true
console.log(arr.constructor === Array); // true
console.log(func.constructor === Function); // true

解释说明:

  1. typeof 操作符:用于检查基本数据类型(如字符串、数字、布尔值等),但对于 null 和对象(包括数组和函数)会返回 "object""function"
  2. instanceof 操作符:用于检查对象是否属于某个构造函数的实例,例如检查一个变量是否为数组或对象。
  3. constructor 属性:可以用来检查对象的具体构造函数,例如判断一个变量是否由 StringNumberArray 等构造函数创建。

上一篇:js linq

下一篇:js 数据类型

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

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

Laravel 中文站