æ¹æ³ä¸»è¦æä¸ç§
转æ¢å½æ°ã强å¶ç±»å转æ¢ãå©ç¨jsåé弱类å转æ¢ã
1. 转æ¢å½æ°ï¼
jsæä¾äºparseInt()åparseFloat()两个转æ¢å½æ°ãåè
æå¼è½¬æ¢ææ´æ°ï¼åè
æå¼è½¬æ¢ææµ®ç¹æ°ãåªæ对Stringç±»åè°ç¨è¿äºæ¹æ³ï¼è¿ä¸¤ä¸ªå½æ°æè½æ£ç¡®è¿è¡ï¼å¯¹å
¶ä»ç±»åè¿åçé½æ¯NaN(Not a Number)ã
ä¸äºç¤ºä¾å¦ä¸ï¼
å¤å¶ä»£ç 代ç å¦ä¸:
parseInt("1234blue"); //returns 1234
parseInt("0xA"); //returns 10
parseInt("22.5"); //returns 22
parseInt("blue"); //returns NaN
parseInt()æ¹æ³è¿æåºæ¨¡å¼ï¼å¯ä»¥æäºè¿å¶ãå
«è¿å¶ãåå
è¿å¶æå
¶ä»ä»»ä½è¿å¶çå符串转æ¢ææ´æ°ãåºæ¯ç±parseInt()æ¹æ³ç第äºä¸ªåæ°æå®çï¼ç¤ºä¾å¦ä¸ï¼
å¤å¶ä»£ç 代ç å¦ä¸:
parseInt("AF", 16); //returns 175
parseInt("10", 2); //returns 2
parseInt("10", 8); //returns 8
parseInt("10", 10); //returns 10
å¦æåè¿å¶æ°å
å«å导0ï¼é£ä¹æ好éç¨åºæ°10ï¼è¿æ ·æä¸ä¼æå¤å°å¾å°å
«è¿å¶çå¼ãä¾å¦ï¼
å¤å¶ä»£ç 代ç å¦ä¸:
parseInt("010"); //returns 8
parseInt("010", 8); //returns 8
parseInt("010", 10); //returns 10
parseFloat()æ¹æ³ä¸parseInt()æ¹æ³çå¤çæ¹å¼ç¸ä¼¼ã
使ç¨parseFloat()æ¹æ³çå¦ä¸ä¸åä¹å¤å¨äºï¼å符串å¿
须以åè¿å¶å½¢å¼è¡¨ç¤ºæµ®ç¹æ°ï¼parseFloat()没æåºæ¨¡å¼ã
ä¸é¢æ¯ä½¿ç¨parseFloat()æ¹æ³ç示ä¾ï¼
å¤å¶ä»£ç 代ç å¦ä¸:
parseFloat("1234blue"); //returns 1234.0
parseFloat("0xA"); //returns NaN
parseFloat("22.5"); //returns 22.5
parseFloat("22.34.5"); //returns 22.34
parseFloat("0908"); //returns 908
parseFloat("blue"); //returns NaN
2. 强å¶ç±»å转æ¢
è¿å¯ä½¿ç¨å¼ºå¶ç±»å转æ¢ï¼type castingï¼å¤ç转æ¢å¼çç±»åã使ç¨å¼ºå¶ç±»å转æ¢å¯ä»¥è®¿é®ç¹å®çå¼ï¼å³ä½¿å®æ¯å¦ä¸ç§ç±»åçã
ECMAScriptä¸å¯ç¨ç3ç§å¼ºå¶ç±»å转æ¢å¦ä¸ï¼
Boolean(value)ââæç»å®çå¼è½¬æ¢æBooleanåï¼
Number(value)ââæç»å®çå¼è½¬æ¢ææ°åï¼å¯ä»¥æ¯æ´æ°ææµ®ç¹æ°ï¼ï¼
String(value)ââæç»å®çå¼è½¬æ¢æå符串ã
ç¨è¿ä¸ä¸ªå½æ°ä¹ä¸è½¬æ¢å¼ï¼å°å建ä¸ä¸ªæ°å¼ï¼åæ¾ç±åå§å¼ç´æ¥è½¬æ¢æçå¼ãè¿ä¼é æææ³ä¸å°çåæã
å½è¦è½¬æ¢çå¼æ¯è³å°æä¸ä¸ªå符çå符串ãé0æ°åæ对象ï¼ä¸ä¸èå°è®¨è®ºè¿ä¸ç¹ï¼æ¶ï¼Boolean()å½æ°å°è¿åtrueãå¦æ该å¼æ¯ç©ºå符串ãæ°å0ãundefinedænullï¼å®å°è¿åfalseã
å¯ä»¥ç¨ä¸é¢ç代ç 段æµè¯Booleanåç强å¶ç±»å转æ¢ã
å¤å¶ä»£ç 代ç å¦ä¸:
Boolean(""); //false â empty string
Boolean("hi"); //true â non-empty string
Boolean(100); //true â non-zero number
Boolean(null); //false - null
Boolean(0); //false - zero
Boolean(new Object()); //true â object
Number()ç强å¶ç±»å转æ¢ä¸parseInt()åparseFloat()æ¹æ³çå¤çæ¹å¼ç¸ä¼¼ï¼åªæ¯å®è½¬æ¢çæ¯æ´ä¸ªå¼ï¼èä¸æ¯é¨åå¼ã示ä¾å¦ä¸ï¼
å¤å¶ä»£ç 代ç å¦ä¸:
ç¨ããæ³ ç»ããæ
Number(false) 0
Number(true) 1
Number(undefined) NaN
Number(null) 0
Number( "5.5 ") 5.5
Number( "56 ") 56
Number( "5.6.7 ") NaN
Number(new Object()) NaN
Number(100) 100
æåä¸ç§å¼ºå¶ç±»å转æ¢æ¹æ³String()æ¯æç®åçï¼ç¤ºä¾å¦ä¸ï¼
å¤å¶ä»£ç 代ç å¦ä¸:
var s1 = String(null); //"null"
var oNull = null;
var s2 = oNull.toString(); //won't work, causes an error
3. å©ç¨jsåé弱类å转æ¢
举个å°ä¾åï¼ä¸çï¼å°±ä¼æç½äºã
å¤å¶ä»£ç 代ç å¦ä¸:
<script>
var str= '012.345 ';
var x = str-0;
x = x*1;
</script>
ä¸ä¾å©ç¨äºjsç弱类åçç¹ç¹ï¼åªè¿è¡äºç®æ¯è¿ç®ï¼å®ç°äºå符串å°æ°åçç±»å转æ¢ï¼ä¸è¿è¿ä¸ªæ¹æ³è¿æ¯ä¸æ¨èç
温馨提示:答案为网友推荐,仅供参考