一. + 运算符拼接运算有优先级
string 1.string与string
console.log("你"+"好")//你好
2.string与number
console.log(3+"你”)//3你
♥eg: var a = 8, b = 2, c = 3; console.log("a" + b + c) // a23, "a"与b拼接成字符串,在与c拼接
♥eg: var a = 8, b = 2, c = 3; console.log("a" + (b + c)) // a5,用()隔离字符串与数字,()内是一体的。
3.string与boolean
console.log("你" + false) // 你false
4string与undefined
console.log("1" + undefined)//1undefined
5.string与null
console.log("1"+null)//1null
number 1.number与boolean
console.log(1 + true) //2 console.log(1 + false)//1 :
隐式类型转换 boolean(true变为1,false变为0)
2.number与undefined
console.log(1+undefined)// NaN(not a number)
3.number与null
console.log(1+null)//1
boolean :遇见字符串(true/false)就是字符串,遇见其余三种,(true/false => 1/0),boolean之间可运算
undefined:遇见字符串,就是字符串,遇见数字,结果为undefined,遇见其他报错(只能和字符串,数字运算)
null:遇见字符串,就是字符串,遇见其余三种数字,为0,null之间可运算
总结1.string拼接优先级(能与其他四种数据类型拼接) > 2 undefined优先级(只能与string拼接,遇见数字NaN,拼接其他报错) > 3number运算优先级 = boolean隐式类型转换优先级 = null隐式类型转换优先级 ( true 1 ; false 0 ) (null 0)
二:变量的作用,不仅可做简单运算,还可接受封装方法中的数据
①prompt("提示文本”,默认参数) [alert("")不支持输入为警示框 ]
eg: var a = prompt("请用户输入手机号码”,138);//假如输入123
console.log(a) ; //123
console.log(typeof a) ;// string,
prompt框示意图:
【注意】:网页中用户输入的数据都是string类型的,这就需要有数据类型转换来迎合运算的需求
三:数据类型的转换方法。
①Number() : 转为number类型【非数值字符串,undefined都会转为NaN】
1.Number("1")//1
2.Number(true)//1 Number(false)//0
3.Number(null) // 0
4.Number(undefined)// NaN
Number("a")//NaN
5.Number("12px")//NaN
1.parseInt(),转为number类型中的int类型,范围较小,
范围:number类型、数字开头的字符串【会将字符串中的字符去掉】
[不含数字字符串、非数字开头字符串、boolean、undefined,null,转为NaN,】
2.parseFloat() ,转为number类型中的float类型,范围较小
范围;number类型、数字开头的字符串,保留一位小数点(若第一位小数点之前有字符,则去掉字符不保留小数点)
【非数字开头字符串、不含数字字符串、boolean、undefined、null转为NaN]
[注意]:parseInt与parseFloat (a,b)括号内可有第二个参数,代表进制,按照几进制来转换
被转换的数可以是8 10 16进制数,内部会先把0x15转成10进制再转成16进
制。
♥:
typeof 里的运算符数字隐式类型转换为parseInt() 与parseFloat(). 单独运算符的隐式类型转换为Number()
运算符涉及隐式类型转换,且隐式转换函数为 parseInt()/parseFloat
typeof 先计算前面的,后参与+运算。
NaN不等于任何东西
num是NaN,但是NaN不等于NaN,NaN是number类型
③:toFixed(n) 保留n位小数
②String() :功能强大,number、boolean、undefined、null 都可被转为字符串
或者直接用字符串拼接
a.toString() 方法,()内不加参数,与String()不同,String()是括号内加参数,且String()能将undefined null 也转化成字符串,而toString 不能将undefined null 转成字符串,会报错,toString()范围小。
因为 typeof number 为string,number是右侧的类型,但本身对于左侧typeof来说是“number"是个字符串。
③Boolean:转为true或者false
范围:0-false 1-true 空字符串-false 非空字符串-true 其他都为false
四:判断方法
isNaN()
isNaN() 括号内会先用Number()转一下,不能转成Number类型的,结果为true
五:已学的API
alert() prompt() Number() parseInt(a,b) parseFloat()【保留一位小数,有特殊情况】 toFixed(n) String() toString() Boolean() isNaN()
六:隐式类型转换
除了isNaN()中的隐式类型转换,运算符基本都有隐式类型转换