js強制轉換和隱式轉換
阿新 • • 發佈:2018-11-07
一、 強制轉換
使用String(),Number(),Boolean()函式強制轉換
var str=100;
var str1='100';
console.log(typeof str); //number
console.log(typeof str1); //string
console.log(typeof String(str)); //string
console.log(typeof Number(str1)); //number
二、隱式轉換
1.字串加數字,數字就會轉成字串。 2.數字減字串,字串轉成數字。如果字串不是純數字就會轉成NaN。字串減數字也一樣。兩個字串相減也先轉成數字。 3.乘,除,大於,小於跟減的轉換也是一樣。 console.log(1+'2') //12 string console.log(1-'2')//-1 number console.log(10-'df') //NaN console.log(10-'10a') //NaN console.log(10*'20') //200 number console.log('10'*'20') //200 number console.log(2/'1') //2 number console.log('2'/'1') //2 number console.log('2'/'ger') //NaN 4. ==時候也會進行隱式轉換() 1.undefined等於null 2.字串和數字比較時,字串轉數字 3.數字為布林比較時,布林轉數字 4.字串和布林比較時,兩者轉數字 console.log(undefined==null) //true console.log('0'==0) //true 字串轉數字 console.log(0==false) //true 布林轉數字 console.log('0'==false) //2個都轉成數字 console.log(null==false) //false console.log(undefined==false)//false