如何用JS判断数据类型

前情:

由于===和!==这两种判断方式非常严格,不仅要求数值内容一致,还要求数据类型也是一致。

一直不知为何判断结果与想要的不一样,后来发现是数据类型不同。

一个是string类型的数字,一个是number类型的数字。

之后遇到相似的失误时应采用以下方式检验。

检验方式:

一、typeof(监测基本类型)

要检测一个变量是不是基本数据类型,typeof是最佳的工具。也就是说,typeof是确定一个变量是字符串、数值、布尔值还是undefined的最佳工具。但如果变量是一个对象或者null,则typeof操作符会都返回object:

var num = 123;
var str = 'abcdef';
var bool = true;
var arr = [1, 2, 3, 4];
var json = {name:'wenzi', age:25};
var func = function(){ console.log('this is function'); }
var und = undefined;
var nul = null;
var date = new Date();
var reg = /^[a-zA-Z]{5,20}$/;
var error= new Error();


console.log(
typeof num,
typeof str,
typeof bool,
typeof arr,
typeof json,
typeof func,
typeof und,
typeof nul,
typeof date,
typeof reg,
typeof error
);

二、instanceof(引用类型)

result = variable instanceof constructor 

console.log(
num instanceof Number,
str instanceof String,
bool instanceof Boolean,
arr instanceof Array,
json instanceof Object,
func instanceof Function,
und instanceof Object,
nul instanceof Object,
date instanceof Date,
reg instanceof RegExp,
error instanceof Error
)
// num : false
// str : false
// bool : false
// arr : true
// json : true
// func : true
// und : false
// nul : false
// date : true
// reg : true
// error : tru

从上面的运行结果我们可以看到,num, str和bool没有检测出他的类型,但是我们使用下面的方式创建num,是可以检测出类型的:

var num = new Number(123); 
var str = new String(‘abcdef’); 
var boolean = new Boolean(true);

也就是说,根据规定,所有引用类型的值都是Object的实例。因此,在检测一个引用类型和Object构造函数时,instanceof操作符始终会返回true。如果使用instanceof操作符检测基本数据类型的值,则该操作符始终返回false,因为基本数据类型不是对象。

ps:vue页面采用vux的XInput框,type是string的时候,绑定的数值也是string。type是number的时候也是string。

猜你喜欢

转载自blog.csdn.net/qq_34633111/article/details/82050921
今日推荐