Recently, I was reading John Resig's masterpiece "Pro JavaScript Techniques", which talked about how to judge the type of JavaScript. The article introduces two methods, one is to use typeof, the other is to use constructor. It is a pity that as the author of jquery, he did not introduce the type judgment method used by jquery at all. But it doesn’t matter, I’ll summarize it for everyone here.
Here I first recommend to everyone a very useful online editor: http://jsfiddle.net/. It provides various versions of three mainstream js frameworks: jquery, mootools, prototype and YUI. You can use it directly when you need to write simple js test programs. This eliminates the need to open editing software and create various types of files. After editing the code, click the [Run] button and everything is done.
1.typeof
Typeof is the most commonly used method when we do type judgment. Its advantage is that it is simple and easy to remember. Its disadvantage is that it cannot judge object, null, array, regexp and custom objects very well.
The following is my test code:
var str ='str';
var arr=['1','2'];
var num=1;
var bool=true;
var obj={name:'test'} ;
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;
function fn(){
alert('this is a function');
}
function User(name){
this.name=name;
}
var user=new User('user');
console.log(typeof str);
console.log(typeof arr);
console.log(typeof num);
console.log(typeof bool);
console.log (typeof obj);
console.log(typeof nullObj);
console.log(typeof undefinedObj);
console.log(typeof reg);
console.log(typeof fn);
console.log(typeof user);
Code running results:
2.constructor
Now introduce a method that is not commonly used, the object constructor constructor. Its advantage is that it supports the judgment of most object types, especially the judgment of custom objects; its disadvantage is that it cannot be used on null and undefined.
The test code is similar to the previous one, the difference is that XXX.constructor is used instead of typeof.
var str='str';
var arr =['1','2'];
var num=1;
var bool=true;
var obj={name:'test'};
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;
function fn(){
alert('this is a function');
}
function User(name) {
this.name=name;
}
var user=new User('user');
console.log(str.constructor);
console.log(arr.constructor);
console.log(num.constructor);
console.log(bool.constructor);
console.log(obj.constructor);
console.log(reg.constructor);
console.log(fn.constructor);
console.log(user.constructor);
console.log(nullObj.constructor);
console.log(undefinedObj.constructor);
When running console.log(nullObj.constructor);, the browser reports an error: Uncaught TypeError: Cannot read property 'constructor' of null. A similar problem also occurs in console.log(undefinedObj.constructor); above: Uncaught TypeError: Cannot read property 'constructor' of undefined.
3.Object.prototype.toString.call()
The last thing to introduce is the method used in jquery, Object.prototype.toString.call(). The advantage is that it supports most types of judgments, and the only disadvantage is that it does not support the judgment of custom objects.
The test code is as follows:
var str='str';
var arr=['1','2'];
var num=1;
var bool=true;
var obj={name:'test'};
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;
function fn(){
alert('this is a function');
}
function User(name){
this.name=name;
}
var user=new User('user');
var toString=Object.prototype.toString;
console.log(toString.call(str));
console.log(toString.call(arr));
console.log(toString.call(num));
console.log(toString.call(bool));
console.log(toString.call(obj));
console.log(toString.call(reg));
console.log(toString.call(fn));
console.log(toString.call(user));
console.log(toString.call(nullObj));
console.log(toString.call(undefinedObj));
console.log(toString.call(user)); 的返回结果为:[object Object],不能做进一步判断。
总结
javascript中经常使用的对象判断方式包括:typeof、constructor和Object.prototype.toString.call()。其中typeof很好理解,他是JavaScript本身支持的语法。constructor很少使用,但是相信大家通过demo也能看懂他代表的意思。至于Object.prototype.toString.call()可能多少会让人有点费解,他和XXX.toString()有什么区别呢,为什么不能直接使用XXX.toString()呢?
我们在浏览器中运行下面的代码:查看运行结果:
null和undefined因为不存在toString()方法,所以会报错,我们就不去管他们了。至于其他对象,通过toString()返回的内容和使用Object.prototype.toString.call()返回的内容差别很大。这是因为Object.prototype.toString()方法被设计用来返回对象类型的。String、Array、Boolean、Regexp、Number和Function都继承自Object,同时也就继承了Object的原型方法toString(),但是他们都对toString()进行了重写。执行xxx.toString()时使用的是重写后的方法,返回的结果自然会和Object.prototype.toString.call()的结果不一致。
通过上面的例子,大家一定对这三种方式有了更深刻的认识,熟悉他们的优缺点,然后可以根据自己的需要选择合适的方式。推荐使用Object.prototype.toString.call()方法,因为他能解决绝大部分情况的判断,在遇到返回值为[object Object]时,再使用constructor辅助判断,看是否是自定义对象。
var str='str';
var arr=['1','2'];
var num=1;
var bool=true;
var obj={name:'test'};
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;
function fn(){
alert('this is a function');
}
function User(name){
this.name=name;
}
var user=new User('user');
console.log(str.toString());
console.log(arr.toString());
console.log(num.toString());
console.log(bool.toString());
console.log(obj.toString());
console.log(reg.toString());
console.log(fn.toString());
console.log(user.toString());
console.log(nullObj.toString());
console.log(undefinedObj.toString());

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
