在es6 判断数据类型
时间: 2023-10-22 08:08:01 浏览: 44
在 ES6 中,可以使用 `typeof` 运算符来判断基本数据类型,例如:
```javascript
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
```
对于对象类型,`typeof` 运算符会返回 "object",此时需要进一步判断具体的对象类型。可以使用 `instanceof` 运算符来判断对象是否属于某个类型,例如:
```javascript
console.log([] instanceof Array); // true
console.log({} instanceof Object); // true
console.log(/regex/ instanceof RegExp); // true
console.log(new Date() instanceof Date); // true
```
另外,ES6 中还新增了 `Symbol` 类型,可以使用 `typeof` 运算符来判断 `Symbol` 类型,例如:
```javascript
console.log(typeof Symbol()); // "symbol"
```
相关问题
js里如何判断数据类型
在JavaScript中可以使用typeof操作符来判断数据类型,它返回一个字符串,表示该值的类型。常见的类型包括:
- "number" 数字类型
- "string" 字符串类型
- "boolean" 布尔类型
- "null" 空值类型
- "undefined" 未定义类型
- "object" 对象类型(包括数组、函数、正则表达式等)
- "symbol" ES6新增的Symbol类型
例如:
```
typeof 123; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof null; // "object"
typeof undefined; // "undefined"
typeof {}; // "object"
typeof []; // "object"
typeof function() {}; // "function"
typeof Symbol(); // "symbol"
```
怎么判断变量的数据类型?
在 JavaScript 中,可以使用 `typeof` 运算符来判断变量的数据类型。`typeof` 运算符返回一个表示数据类型的字符串。
以下是一些常见的数据类型及其对应的 `typeof` 返回值:
- `undefined`:表示未定义的值。使用 `typeof` 判断时,返回 `'undefined'`。
- `boolean`:表示布尔值。使用 `typeof` 判断时,返回 `'boolean'`。
- `number`:表示数字。使用 `typeof` 判断时,返回 `'number'`。
- `string`:表示字符串。使用 `typeof` 判断时,返回 `'string'`。
- `symbol`:表示符号(ES6 新增)。使用 `typeof` 判断时,返回 `'symbol'`。
- `bigint`:表示大整数(ES2020 新增)。使用 `typeof` 判断时,返回 `'bigint'`。
- `object`:表示对象(包括数组、函数、日期等)。使用 `typeof` 判断时,返回 `'object'`。请注意,`typeof null` 返回 `'object'`,这是一个历史遗留问题。
- `function`:表示函数。使用 `typeof` 判断时,返回 `'function'`。
以下是使用 `typeof` 运算符判断变量数据类型的示例:
```javascript
const undefinedVariable = undefined;
console.log(typeof undefinedVariable); // 'undefined'
const booleanVariable = true;
console.log(typeof booleanVariable); // 'boolean'
const numberVariable = 42;
console.log(typeof numberVariable); // 'number'
const stringVariable = 'Hello';
console.log(typeof stringVariable); // 'string'
const symbolVariable = Symbol('foo');
console.log(typeof symbolVariable); // 'symbol'
const bigintVariable = BigInt(9007199254740991);
console.log(typeof bigintVariable); // 'bigint'
const objectVariable = { name: 'John' };
console.log(typeof objectVariable); // 'object'
const arrayVariable = [1, 2, 3];
console.log(typeof arrayVariable); // 'object'
const functionVariable = function() {};
console.log(typeof functionVariable); // 'function'
```
需要注意的是,`typeof` 运算符对于对象(包括数组和函数)返回的都是 `'object'`。如果需要更准确地判断对象的具体类型,可以使用其他方法,比如 `Array.isArray()` 判断是否为数组,`instanceof` 运算符判断是否为特定类型的实例等。