这个变量是数组还是对象呢?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1369个文字,预计阅读时间需要6分钟。
在JavaScript中,判断一个变量的类型主要有以下几种方法:
1. `typeof` 操作符
2.`instanceof` 操作符
3.`Object.prototype.toString.call()`
1. `typeof` 操作符
`typeof` 是最常用的类型判断方法,它可以返回以下几种字符串:
- `undefined`:当变量未定义时。
- `number`:当变量是数字时。- `string`:当变量是字符串时。- `boolean`:当变量是布尔值时。- `object`:当变量是对象时(包括数组、函数等)。- `function`:当变量是函数时。例如:
javascriptlet a=10;console.log(typeof a); // 输出: number
let b=hello;console.log(typeof b); // 输出: string
let c=true;console.log(typeof c); // 输出: boolean
let d={};console.log(typeof d); // 输出: object
let e=function() {};console.log(typeof e); // 输出: function
需要注意的是,`typeof` 对于基本类型和对象类型的判断是准确的,但对于数组、正则表达式等特殊对象类型,它只能返回 `object`。
本文共计1369个文字,预计阅读时间需要6分钟。
在JavaScript中,判断一个变量的类型主要有以下几种方法:
1. `typeof` 操作符
2.`instanceof` 操作符
3.`Object.prototype.toString.call()`
1. `typeof` 操作符
`typeof` 是最常用的类型判断方法,它可以返回以下几种字符串:
- `undefined`:当变量未定义时。
- `number`:当变量是数字时。- `string`:当变量是字符串时。- `boolean`:当变量是布尔值时。- `object`:当变量是对象时(包括数组、函数等)。- `function`:当变量是函数时。例如:
javascriptlet a=10;console.log(typeof a); // 输出: number
let b=hello;console.log(typeof b); // 输出: string
let c=true;console.log(typeof c); // 输出: boolean
let d={};console.log(typeof d); // 输出: object
let e=function() {};console.log(typeof e); // 输出: function
需要注意的是,`typeof` 对于基本类型和对象类型的判断是准确的,但对于数组、正则表达式等特殊对象类型,它只能返回 `object`。

