因為js是一種弱型別語言,在宣告變數時不必宣告變數型別;變數的型別由執行中儲存的資料型別決定,因此變數的型別是隨機變化的,為此為保證**執行的嚴謹性和**執行時因隱式轉換而導致變數型別的變化所致出現異常情況,我們經常需要對變數型別進行驗證處理。因此我們在寫**時要對自己定義的變數型別進行有效的管理,這樣能避免很多意外bug和提高debug的效率。
js總共有7種資料型別,如下所示:
1、 6種原始資料型別
1)string
2) number
3) boolean
4) null
5) undefine
6) symbol (es6)
2、復合資料型別
1) object
1、typeof
typeof操作符能辨別基本的資料型別,並且返回值為表示該資料型別的字串 ; 但是其能力有限,只能用於來區別原始資料型別,對於其object型別中的array、date 、regexp 及其 null 型別無法細分出
注意:typeof(null) = ' object '
null型別判斷方法:
variable === null // true 為 null
variable == null // true 為 null 或者 undefined
2、 instanceof
用法:object instanceof constructor
instanceof 運算子用來檢測乙個建構函式的prototype屬性是否存在乙個物件的原型鏈上,即檢測該物件是否是乙個建構函式的例項化
(1)可以通過object.getprototypeof(object)方法來檢視該物件的原型,即該物件內部屬性[[prototype]]的值
如果 object.getprototypeof(object) === constructor.prototype
則該所檢測物件一定是所測試的建構函式的例項化
var arr = ,因此我們可以通過 instanceof 運算子對object型別的資料進一步判斷來區分 array、date 、regexp 及其 null 型別reg = /\bis\b/g ,
str1 = new
string(),
str2 = 'aaa';
arr
instanceof array //
true
arr instanceof object //
true
arr instanceof regexp //
false
reg
instanceof regexp //
true
str1 instanceof string //
true
str2 instanceof string //
false
3、constructor屬性
例項化的物件都有constructor屬性,其constructor屬性指標指向的是建構函式,可用來判斷未知物件的型別
所以上面的判斷方法也可以寫成下面的判斷方式
arr.constructor === array //4、object.prototype.tostring.call()true
arr.constructor === object //
true
arr.constructor === regexp //
false
reg.constructor === regexp //
true
str.constructor === string //
true
a = 'hello'b =
c = function(){}
object.tostring.call(a) === "[object string]"
object.tostring.call(b) === "[object array]"
object.tostring.call(c) === "[object function]"
js資料型別
一.原始資料型別 1.typeof 運算子。var a alert typeof a 輸出結果為 undefined 2.undefined 未定義 型別 當變數未定義時,該變數值被預設為undefined 如 var a alert typeof a 輸出結果為 undefined 注意值unde...
js資料型別
js 基本資料型別 undefined null boolean number string js 操作符 typeof檢測給定變數的資料型別。返回值表示的型別 undefined 值未定義。boolean 值為布林型別。string 值為字串。number 值為數字。object 值為物件或nul...
js資料型別
var num 1,boo true,aa null,bb,str mary arr 1,2,4,8 obj arrnew new array 1,2,3 strnew new string 1,2,3 用 typeof 檢測變數的型別 console.log number typeof num n...