js判断数据类型的方法
时间: 2023-11-10 09:16:00 浏览: 91
在JavaScript中,有多种方法可以判断数据类型,以下是一些常用的方法:
1. typeof:用于判断基本数据类型,如字符串、数字、布尔值、undefined,但对于对象、数组、null等类型判断不准确。
2. instanceof:用于判断一个对象是否属于某个类,如判断一个对象是否为数组。
3. Object.prototype.toString.call():可以判断任何数据类型,包括基本数据类型和引用类型。
4. Array.isArray():用于判断一个对象是否为数组。
5. isNaN():用于判断一个值是否为NaN。
示例代码:
```
console.log(typeof "hello world"); // 输出:string
console.log(typeof 123); // 输出:number
console.log(typeof true); // 输出:boolean
console.log(typeof {}); // 输出:object
console.log(typeof []); // 输出:object
console.log(typeof null); // 输出:object
console.log(typeof undefined); // 输出:undefined
var arr = [1, 2, 3];
console.log(arr instanceof Array); // 输出:true
var obj = {};
console.log(Object.prototype.toString.call(obj)); // 输出:[object Object]
console.log(Array.isArray(arr)); // 输出:true
console.log(isNaN(123)); // 输出:false
console.log(isNaN("123")); // 输出:false
console.log(isNaN("hello")); // 输出:true
```
阅读全文
相关推荐



















