您的位置:首页 > Web前端 > JavaScript

js判断数据类型方法。

2018-11-08 17:32 549 查看

JS判断类型的方式一共有以下几种,typeof、instanceof、 constructor、 prototype、还有第三方库。

分开说明:

typeof

// Numbers
typeof 37 === ‘number’;
typeof 3.14 === ‘number’;
typeof Math.LN2 === ‘number’;
typeof Infinity === ‘number’;
typeof NaN === ‘number’; // 尽管NaN是"Not-A-Number"的缩写
typeof Number(1) === ‘number’; // 但不要使用这种形式!

// Strings
typeof “” === ‘string’;
typeof “bla” === ‘string’;
typeof (typeof 1) === ‘string’; // typeof总是返回一个字符串
typeof String(“abc”) === ‘string’; // 但不要使用这种形式!

// Booleans
typeof true === ‘boolean’;
typeof false === ‘boolean’;
typeof Boolean(true) === ‘boolean’; // 但不要使用这种形式!

// Symbols
typeof Symbol() === ‘symbol’;
typeof Symbol(‘foo’) === ‘symbol’;
typeof Symbol.iterator === ‘symbol’;

// Undefined
typeof undefined === ‘undefined’;
typeof declaredButUndefinedVariable === ‘undefined’;
typeof undeclaredVariable === ‘undefined’;

// Objects
typeof {a:1} === ‘object’;

// 使用Array.isArray 或者 Object.prototype.toString.call
// 区分数组,普通对象
typeof [1, 2, 4] === ‘object’;

typeof new Date() === ‘object’;

// 下面的容易令人迷惑,不要使用!
typeof new Boolean(true) === ‘object’;
typeof new Number(1) === ‘object’;
typeof new String(“abc”) === ‘object’;

// 函数
typeof function(){} === ‘function’;
typeof class C{} === ‘function’
typeof Math.sin === ‘function’;
typeof new Function() === ‘function’;
在实际的项目应用中,typeof只有两个用途,就是检测一个元素是否为undefined,或者是否为function,还有就是判断变量是否存在。

例子:

if(a){
console.log('find!'); // Uncaught ReferenceError: a is not defined
}
// 通常这种情况如果没有声明会报错,只能通过下面这种方式去解决

if(typeof a!='undefined'){
console.log('find');
}

instanceof

nstanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置

var a = [1,2,3];
var b = new Date();
var c = function(){};

alert(a instanceof Array) ---------------> true
alert(b instanceof Date)
alert(c instanceof Function) ------------> true
alert(c instanceof function) ------------> false

constructor

var o = {};
o.constructor === Object; // true

var o = new Object;
o.constructor === Object; // true

var a = [];
a.constructor === Array; // true

var a = new Array;
a.constructor === Array // true

var n = new Number(3);
n.constructor === Number; // true

var a = [1,2,3];
var b = new Date();
var c = function(){};

alert(a.constructor === Array) // true
alert(b.constructor === Date) // true
alert(c.constructor === Function) // true

Object.prototype.toString
可以通过toString() 来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为thisArg。

var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: