parseInt/类型转换/字符串
1.pa'rseInt整型
1.1parseInt必须以数字开头的
var topVal = parseInt("28px"); console.log(topVal); //28
1.2非数字开头时,控制器打印出来是NaN
var z = parseInt("abc52"); console.log(z); //NaN
1.3两个参数情况下,16进制
console.log(parseInt("0xf", 16)) //15
2.parseFloat浮点数
var e = parseInt("12.34.26"); console.log(e) //12 var d = parseFloat("12.34.26"); console.log(d); //12.34
var b = parseInt("0123abc"); console.log(b); //123 var dd = parseFloat("0123abc"); console.log(dd); //123 var ee = Number("0123abc"); console.log(ee); //NaN var cc = Number("18"); console.log(cc); //18
注意:当把一个字符串中数字提取出来,最好用parseInt或者parseFloat,前提条件必须是数字开头(125abc),而不是其他开头(abc123);不太推荐Number强制转换
2.转换为字符串 string与toString
<h2>转换为字符串类型</h2> <script> var ids = 65352; var idstr = ids.toString(); console.log(idstr);//65352 console.log(typeof idstr)//string console.log(String(ids))//65352 </script>
3.转为布尔Boolean
<h2>转换为布尔类型</h2> <script> var ids = true; var idstr = false; console.log(typeof ids);//boolean console.log(typeof idstr)//boolean </script>
3.1类型转换
(1)除0之外的所有数字,转换为布尔型都为true
(2)除""之外的所有字符,都转为布尔型都为true
(3)null和undefined转换为布尔型为false
<h2>除0之外的所有数字,转换为布尔型都为true</h2> <script> var x = 0; var y = 1; console.log(Boolean(x));//false console.log(Boolean(y))//true </script>
<h2>除""之外的所有字符,都转为布尔型都为true</h2> <script> var stringWords = "welcome"; var stringKong = "";//空的 var kongge = " "; console.log(Boolean(stringKong));//false console.log(Boolean(stringWords))//true console.log(Boolean(kongge))//true 空格布尔型也是true </script>
<h2>null和undefined转换为布尔型为false</h2> <script> var y; var x = null; console.log(Boolean(y))//false console.log(Boolean(x))//false </script>