js數據類型轉換
阿新 • • 發佈:2019-01-10
種類 defined truct nan new 數據類型 通過 eval 返回
1.通過typeof查看數據類型
typeof 3.14 // 返回 number typeof NaN // 返回 number typeof "John" // 返回 string typeof false // 返回 boolean typeof [1,2,3,4] // 返回 object typeof {name:‘John‘, age:34} // 返回 object typeof new Date() // 返回 objecttypeof function () {} // 返回 function typeof myCar // 返回 undefined(如果myCar沒有聲明) typeof undefined // 返回 undefined typeof null // 返回 object
typeof的返回只有number、string、boolean、object、function、undefined五種類型
如果要查看的是數組、對象、日期、或者null,返回值都是object,無法通過typeof來判斷他們的類型
2.通過constructor屬性返回構造函數
(1234).constructor //function Number() { [native code] } NaN.constructor //function Number() { [native code] } ‘hello‘.constructor //function String() { [native code] } false.constructor //function Boolean() { [native code] }[1,2,3,4].constructor //function Array() { [native code] } {name:‘John‘, age:34}.constructor //function Object() { [native code] } new Date().constructor //function Date() { [native code] } function(){}.constructor //function Function() { [native code] }
constuction屬性返回的構造函數有七種,unll和undefined沒有構造函數
3.自動類型轉換
數字 + 字符串 : 將數字轉化為字符串,再與後面字符串的進行拼接
數字 + 布爾值:true轉化為1,false轉化為0,再與數字進行相加
字符串 + 布爾值:按照字符串進行拼接
document.getElementById("demo").innerHTML = myVar; myVar = {name:"Fjohn"} // toString 轉換為 "[object Object]" myVar = [1,2,3,4] // toString 轉換為 "1,2,3,4" myVar = new Date() // toString 轉換為 "Fri Jul 18 2014 09:08:55 GMT+0200"
4.數字、布爾值、日期強制轉化為字符串
String(123)、(123).toString()都可將數字轉化為字符串
String(true)、false.toString()都可將數字轉化為字符串
String(new Date()) 、(new Date()).toString()都可將日期轉化為字符串
5.數字類型的字符串、布爾值、日期強制轉化為數字
Number(‘3.14‘)可將字符串3.14轉化為數字3.14,Number(‘‘)返回0,Number("99 88")返回NaN
Number(false)返回0,Number(true) 返回1
d = new Date(),Number(d)和d.getTime()可將日期轉換為數字
parseInt( ) 將浮點數、字符串類型的數字、以數字開頭的字符串轉化為整數,轉換失敗時會得到NaN
parseFloat()強制轉換為浮點數
6.eval():將字符串強制轉換為表達式並返回結果,例如eval(‘1+4‘)=5
js數據類型轉換