写一个js判断类型的函数
时间: 2024-02-18 21:01:57 浏览: 27
可以定义一个函数 `getType`,通过 `typeof` 操作符来判断传入参数的类型,代码如下:
```js
function getType(value) {
const type = typeof value;
switch (type) {
case 'number':
return Number.isNaN(value) ? 'nan' : 'number';
case 'object':
return Array.isArray(value) ? 'array' : 'object';
default:
return type;
}
}
```
其中,针对数字类型还需要判断是否为 `NaN`。此外,为了区分对象和数组类型,使用 `Array.isArray` 方法进行判断。
相关问题
写一个js判断所有类型的函数并返回结果
可以定义一个函数 `getTypeOf`,通过 `Object.prototype.toString.call(value)` 方法来判断传入参数的类型,代码如下:
```js
function getTypeOf(value) {
const typeStr = Object.prototype.toString.call(value);
const type = typeStr.split(' ')[1].slice(0, -1).toLowerCase();
switch (type) {
case 'number':
return Number.isNaN(value) ? 'nan' : 'number';
case 'object':
return Array.isArray(value) ? 'array' : 'object';
default:
return type;
}
}
```
其中,`Object.prototype.toString.call(value)` 方法可以返回类似于 `[object Type]` 的字符串,通过对其进行解析获得值的类型。针对数字类型还需要判断是否为 `NaN`。此外,为了区分对象和数组类型,使用 `Array.isArray` 方法进行判断。
前端封装一个函数判断string类型
可以通过正则表达式来判断一个字符串是否为纯字符串类型。以下是一个简单的函数示例:
```javascript
function isString(str) {
return typeof str === 'string' && /^[a-zA-Z]+$/.test(str);
}
```
该函数使用了 `typeof` 操作符来检查参数是否为字符串类型。接着,它使用了正则表达式 `/^[a-zA-Z]+$/` 来检查字符串是否只包含字母。如果字符串只包含字母,函数会返回 `true`,否则返回 `false`。你可以根据需要修改正则表达式来适应不同的字符串格式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)