JavaScript 中查看类型的方法:typeof 运算符返回原始类型 (string、number 等)。instanceof 运算符检查对象是否属于某个构造函数或其子类。Object.prototype.toString.call() 返回对象的类型格式为 "[object Type]”。Array.isArray() 检查变量是否为数组。Date.prototype.toString() 返回日期对象的字符串表示,可判断对象类型是否为 Date。
如何查看 JavaScript 类型
在 JavaScript 中,可以通过以下方法查看变量或表达式的类型:
1. typeof 运算符
typeof 运算符返回变量或表达式的原始类型(string、number、boolean、undefined、null 等)。
console.log(typeof "hello"); // "string" console.log(typeof 10); // "number" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined"
2. instanceof 运算符
instanceof 运算符用于检查对象是否属于某个构造函数或其子类。
console.log("hello" instanceof String); // false console.log(new String("hello") instanceof String); // true
3. Object.prototype.toString.call() 方法
Object.prototype.toString.call() 方法返回对象的类型,格式为 "[object Type]"(例如 "[object String]"、"[object Number]" 等)。
console.log(Object.prototype.toString.call("hello")); // "[object String]" console.log(Object.prototype.toString.call(10)); // "[object Number]"
4. Array.isArray() 方法
Array.isArray() 方法用于检查变量是否为数组。
console.log(Array.isArray("hello")); // false console.log(Array.isArray([1, 2, 3])); // true
5. Date.prototype.toString() 方法
Date.prototype.toString() 方法返回日期对象的字符串表示,可以用来判断对象的类型是否为 Date。
console.log(new Date().toString() instanceof Date); // true
以上就是如何查看js类型的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号