类型转换是一种将一种数据类型转换为另一种数据类型的方法。
一、运算符的类型
typeof运算符可以帮助你找到你的变量的类型。typeof运算符返回一个变量或表达式的类型。
例:
<!DOCTYPEhtml> <html> <title>项目</title> <bodystyle="background-color:aqua;"> <h1>JavaScripttypeof运算符</h1> <p>typeof运算符返回变量或表达式的类型:</p> <script> document.write( typeof""+"<br>"+ typeof"Json"+"<br>"+ typeof"42"+"<br>"+ typeof42+"<br>"+ typeoftrue+"<br>"+ typeoffalse+"<br>"+ typeofundefined+"<br>"+ typeofnull+"<br>"+ typeof{ name:"Json", age:22 }+"<br>"+ typeof[2,4,6,8]+"<br>"+ typeof functionmyFunc(){} ); </script> <p><b>注意:</b><b>typeof</b> 运算符为数组返回"object",因为在JavaScript数组中是对象。</p> </body> </html>
可以使用typeof运算符查找JavaScript变量的数据类型。
二、类型转换
1. 将值转换为字符串
通过调用String()函数 或 x.toString()方法将值显式转换为字符串。通过该String()函数,将值true传递给参数,从而将布尔值转换为字符串。
String(true);//返回"true" 数字传递给函数。
String(108);//返回"108" 使用typeof运算符检查类型。
typeofString(true);//返回"string" typeofString(108);//返回"string" x.toString()以类似的方式使用方法。可以将x替换为变量。
<script> lettemp=108; document.querySelector("#output").innerHTML=temp.toString(); </script> 或者,可以将值放在括号内,而不是使用x.toString()进行变量设置。
(9048).toString();//返回"9048" (false).toString();//返回"false" (50+20).toString();//返回"70"
通过使用String()或,x.toString()可以将Boolean或number数据类型的值显式转换为字符串值,以确保的代码按预期运行。
2. 将值转换为布尔值
将数字或字符串转换为布尔值,使用该Boolean()函数。任何被解释为空的值(例如数字0,空字符串或未定义或NaN或null的值)都将转换为false。
<script> document.write( Boolean(0)+"<br>"+ Boolean("")+"<br>"+ Boolean(undefined)+"<br>"+ Boolean(NaN)+"<br>"+ Boolean(null) ); </script>
其他值将转换为true,包括由空格组成的字符串文字。
<script> document.write( Boolean(50)+"<br>"+ Boolean(-50)+"<br>"+ Boolean(3.14)+"<br>"+ Boolean("false")+"<br>"+ Boolean("HelloWorld") ); </script>
注意:
“ 0”作为字符串文字将转换为true,因为它是一个非空的字符串值。
Boolean("0");//返回true
将数字和字符串转换为布尔值可以使能够评估二进制内的数据,并且可以利用它来指定程序中的指定流。
3. 将数组转换为字符串
该toString()方法将数组转换为(逗号分隔)数组值的字符串。
varmonths=["Jan","Feb","Mar","Apr","May"]; document.getElementById("result").innerHTML=months.toString();
该join()方法还将数组的所有元素转换为新的字符串。
此方法的行为类似于toString(),还可以指定分隔符。
<script> varfruits=["Banana","Apple","Mango"]; varresult=document.getElementById("result"); result.innerHTML=fruits.join("")+"<br>"; result.innerHTML+=fruits.join("")+"<br>"; result.innerHTML+=fruits.join("+")+"<br>"; result.innerHTML+=fruits.join("/")+"<br>"; result.innerHTML+=fruits.join("©"); </script>
4. 将字符串转换为数组
该split()方法将字符串拆分为子字符串数组,然后返回新数组,使用该split()方法通过以表示的空格字符分隔数组 " "。
varstr='HelowWorldisanAmfhyeaadehe.'; vararr=str.split("");
arr变量中有了一个新数组,可以使用索引号访问每个元素。
arr[0];//Air arr[2];//is 使用“ i”作为分隔符。
<script> functionmyFunc(){ varstr='AirPollutionisintroductionofchemicalstotheatmosphere.'; vararr=str.split("i"); document.getElementById('x').innerHTML=arr; } </scrip
如果将空字符串("")用作分隔符,则该字符串将转换为字符数组。
<script> functionmyFunc(){ varstr='AirPollutionisintroductionofchemicalstotheatmosphere.'; vararr=str.split(""); document.getElementById('x').innerHTML=arr; } </script>
三、总结
本文基于JavaScript 基础。介绍了JavaScript 类型转换,对于每一种类型转换,对于每一种转换需要注意的点,在实际项目遇到的难点,提供了有效的解决方案。
通过案例的分析,希望能够帮助读者更好的理解JavaScript 。
原文地址:https://mp.weixin.qq.com/s/BkD2xcCkYjXPLUjhiDqhGA