判斷資料型別

2022-08-15 06:30:18 字數 2054 閱讀 9254

1

var arr = [1,2,3];

2 console.log(arr.tostring());//

1,2,334

var bo = true

;5 console.log(bo.tostring());//

true67

var date = new

date();

8 console.log(date.tostring());//

fri nov 17 2017 15:18:18 gmt+0800 (中國標準時間)910

var m = function

()13 console.log(m.tostring());//

function ()

1415

var num = 123;

16 console.log(num.tostring());//

12317

18var s = "abc";

19 console.log(s.tostring());//

abc20

21var a=;

22 console.log(a.tostring());//

[object object]

2324 console.log(typeof(arr));//

object

25 console.log(typeof(null));//

object

26 console.log(typeof(a));//

object

27 console.log(object.prototype.tostring.call(arr));//

[object array]

28 console.log(object.prototype.tostring.call(null));//

[object null]

29 console.log(object.prototype.tostring.call(a));//

[object object]

通過上面例子我們則可以看到tostring()為何能區分陣列,null以及物件。typeof對陣列,null以及物件判斷的結果都是object,所以區分它們三者的一種辦法即使用object的原型上的方法tostring

5math.max.call(null, 3, 5, 4); //

5對普通函式呼叫,我們通常把this繫結為null

所以object.prototype.tostring.call(arr))是將this指定到這個arr上了。

下面系統說一下判斷資料是否為陣列的方法:

法一:

function

isarray(obj)

else

}

法二:

array.isarray(obj);   //

obj是待檢測的物件

法三:

注意:instanceof運算子左邊是子物件(待測物件),右邊是父建構函式(這裡是array),

即:子物件 instanceof  父建構函式 

instance: 例項:凡是用new 建構函式()建立出的物件,都稱為是建構函式的例項

arr instanceof array

法四:

原理:檢測乙個物件是否是array的原型(或處於原型鏈中,不但可檢測直接父物件,還可檢測整個原型鏈上的所有父物件)

使用方法: parent.isprototypeof(child)來檢測parent是否為child的原型;

需注意的是isprototypeof()函式實現的功能和instancof運算子非常類似;

array.prototype.isprototypeof(arr) //

true表示是陣列,false不是陣列

法五:利用建構函式constructor

obj.constructor == array

判斷資料型別

typeof 如果使用typeof來判斷資料型別的話,結果如下 var num new number 123 var str new string 1223 var bool new boolean false console.log typeof 123,number typeof num,obj...

判斷資料型別

typeof 判斷基本資料型別 不能區分null object 弊端不能區分 陣列 物件 和 null console.log typeof dddd console.log typeof 12 console.log typeof true console.log typeof undefined...

資料型別判斷

可以判斷基本資料型別,它返回的資料型別的字串 返回結果只能包括number,boolean,string,function,object,undefined 但不能判斷null array,可以使用typeof判斷變數是否存在 如if typeof a undefined 但是對於一些建立的物件,它...