自动类型转换
2025年4月30日小于 1 分钟
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自动类型转换</title>
</head>
<body>
<script type="text/javascript">
//一类情况
//+ 作为运算符
var a=1+2;
document.write(a+"<br/>");
//+ 只要有字符串参与运算 就作为连接符
var b=1+'2';
document.write(b+"<br/>");
document.write(typeof(b)+"<br/>");
//如前面是运算,则先运算,后连接
var c=1+2+'3';
document.write(c+"<br/>");
document.write(typeof(c)+"<br/>");
var d=1+'2'+3;
document.write(d+"<br/>");
document.write(typeof(d)+"<br/>");
var e='1e'+2+3;
document.write(e+"<br/>");
document.write(typeof(e)+"<br/>");
//除了+ 其他运算符正常
var f=2-'1';
document.write(f+"<br/>");
document.write(typeof(f)+"<br/>");
//如果无法计算的字符串参与运算 结果为NaN
var g=2-'1e';
document.write(g+"<br/>");
document.write(typeof(g)+"<br/>");
//二类情况
if(g)
{
alert('哈哈哈');
}
else
{
alert('呜呜呜');
}
</script>
</body>
</html>