日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

js判断对象类型

發布時間:2023/12/2 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 js判断对象类型 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.typeof

typeof只能判斷區分基本類型,number、string、boolean、undefined和object,function;

typeof 0; //number; typeof true; //boolean; typeof undefined; //undefined; typeof "hello world" //string; typeof function(){}; //function;typeof null; //object typeof {}; //object; typeof []; //object

從上例我們可以看出,?typeof??判斷對象和數組都返回object,因此它無法區分對象和數組。

2.instanceof

var a={}; a instanceof Object //true a intanceof Array //false var b=[]; b instanceof Array //true b instanceof Object //true

因為數組屬于object中的一種,所以數組instanceof object,也是true.

var c='abc'; c instanceof String; //false var d=new String(); d instanceof String //true

instanceof不能區分基本類型string和boolean,除非是字符串對象和布爾對象。如上例所示。

3.constructor? 

var o={}; o.constructor==Object //true var arr=[]; arr.constructor==Array //true arr.constructor==Object //false

可以看出constructor可以區分Array和Object。

var n=true; n.constructor==Boolean //true var num=1; num.constructor==Number //true var str='hello world'; str.constructor==String //true

var num=new Number();

num.constructor==Number? ?//true

?

不過要注意,constructor屬性是可以被修改的,會導致檢測出的結果不正確

function Person(){} function Student(){} Student.prototype = new Person(); var John = new Student(); console.log(John.constructor==Student); // false console.log(John.constructor==Person); // true
除了undefined和null,其他類型的變量均能使用constructor判斷出類型.

4.Object.prototype.toString.call()? ?---------最好用

Object.prototype.toString.call(123) //"[object Number]" Object.prototype.toString.call('str') //"[object String]" Object.prototype.toString.call(true) //"[object Boolean]" Object.prototype.toString.call({}) //"[object Object]" Object.prototype.toString.call([]) //"[object Array]"

封裝一個判斷數組和對象的方法

function typeObj(obj){var type=Object.prototype.toString.call(obj);if(type=='[object Array]'){return 'Array';}elseif(type=='[object Object]'){return 'Object';}else{return "obj is not object or array"}}

Object.prototype.toString方法的在被調用的時候,會執行如下的操作步驟:?

1. 獲取對象的類名(對象類型)。??

[[Class]]是一個內部屬性,所有的對象(原生對象和宿主對象)都擁有該屬性.在規范中,[[Class]]是這么定義的:?
內部屬性,[[Class]] 一個字符串值,表明了該對象的類型。
2. 然后將[object? 獲取的對象類型的名]組合為字符串?
3. 返回字符串 “[object Array]”?。

5.jQuery中的? $.type接口

$.type(obj) ;

$.isArray(obj);

$.isFunction(obj);

$.isPlainObject(obj);

$.type([]) //array $.isArray([]); //true $.isFunction(function(){}); //true $.isPlainObject({}); //true $.isPlainObject([]); //false

?


更多專業前端知識,請上 【猿2048】www.mk2048.com

總結

以上是生活随笔為你收集整理的js判断对象类型的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。