1. 程式人生 > >Js隱式轉換筆記整理

Js隱式轉換筆記整理

dea eai pxe rod aid ann aix mtu rbf

1.js的數據類型: Number、Boolean、String、Undefined、Null、Symbol(es6新定義的)和Object(ps:Array是特殊的Object) typeof返回6種類型:number boolean string object undefined function 技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片 ps:s是undefined是因為是一個未初始化的變量 2.轉換規則: 對象——>字符串——>數值——>布爾 eg.技術分享圖片技術分享圖片技術分享圖片技術分享圖片 []==true; //false []轉換為字符串‘‘,然後轉換為數值0,true直接轉換為數值1,所以不相等,輸出false []==false //true []先轉換為字符串‘‘,然後轉換為數值0,false直接轉換為數值0,相等,輸出true ![]==false //true ![]直接轉換為布爾值再取反,轉換為布爾值時,除空字符串(‘‘),NaN,0,null,undefined這幾個之外返回的都是true
,取反false則轉換為0;false轉換為數值0,相等,輸出true undefined==null //true undefined和null比較返回true,二者和其他值比較返回false Number(null) //0 3.常見的隱式轉換 以加號運算時,String和其他類型時,其他類型都會轉換為String;其他情況,都轉換為Number類型。 ps: 1.Undefined轉換為Number時為NaN,任何Number與NaN相加都為NaN,而NaN並不等於它自身。也就是說NaN!==NaN,據說isNaN並不可靠。 2.加感嘆號後,轉換為Boolean類型為false的有:null,0,‘‘,undefined,NaN,false 技術分享圖片技術分享圖片
技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片 3.number()和parseInt()都可以將對象轉化為Number類型,Number函數要比parseInt函數嚴格很多。基本上,只要有一個字符無法轉換為數值,整個字符串就會被轉為NaN 技術分享圖片技術分享圖片 Number類型會先調用valueOf(),String類型會先調用toString(),如果結果是原始值,則返回原始值,否則繼續用toString或valueOf(),繼續計算,若不是原始值,則拋出一個類型錯誤。 eg. 技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片 {}+[] //js在運行時,將第一次{}認為是空的代碼塊,相當於 +[] []+[] //表示字符串"" 另外: +[]===0 -[]===0 ~[]===-1 //~[]按位非空數組,其值為-1 ~-~[]===-2 ~-~-~-~-~[]===-5 ~-~-~-~-~[]+~[]===-6 ~+~[]===0 ~+~+~[]===-1 ~+~+~+~[]===0 Ps:~表示按位取反,有一個規律,~x=-(x+1)
eg. ~-5=4 ~9=-10 4.其他 toString: [1].toString(); //"1" [1,2,3].toString(); //"1,2,3" ["a",1,"b",2].toString(); //"a,1,b,2" ToNumber: 技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片技術分享圖片 stackoverflow給了一些關於第二個變成NaN的解釋。 To provide further proof that this toString() conversion happens before the ToNumber conversion, we can actually modify Array.prototype.toString to provide a different result, and any ToNumber conversions will use that modified result.
1 Array.prototype.toString=function(){
2     var n=0;
3     for(var i=0;i<this.length;i++){
4         n+=this[i];
5     }
6     return n;
7 };
Here I‘ve replaced the toString on Array.prototype with a function that sums the Array. Obviously you don‘t want to do this, but we can show how we will now get a different result.
1     Number([1,2,3]); //6
2     +[1,2,3];   //6
So now you can see that the ToNumber conversion of our Array that would previously have resulted in NaN is now resulting in the sum of the items in the Array. 重寫原型後: 技術分享圖片技術分享圖片技術分享圖片技術分享圖片 emmm,都是從別人那裏整理來的,如果錯了還請指正,留給自己以後翻看。

Js隱式轉換筆記整理