一、转换为字符串
1. 变量.String();
var num = 1;
alert(num.toString(num));
2.String() 强制转换
var num = 1;
alert(String(num));
3.加号拼接字符串 隐式转换
var num = 1;
alert(num + '我是字符串');
二、转换为数字型
1.parseInt(String),得到的是整数
console.log(parseInt('3.14'));//3
console.log(parseInt('120px'));//120
cosole.log(parseFloat('rem120px'));//NaN
2.parseFloat(变量)
cosole.log(parseFloat('3.14'));
3.利用Number(变量)
console.log(Number('12'));
4.利用算数运算 - * / 隐式转换
console.log('12' - 0);
console.log('123' - '120');//3
三、转换为布尔型
console.log(Boolean(''));//false
console.log(Boolean(0));//false
console.log(Boolean(NaN));//false
console.log(Boolean(null));//false
console.log(Boolean(undefined));//false
四、案例
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script>
var year = prompt('请输入您的出生年份');//输入框里的内容为字符串型
var age = 2021 - year//数字型减去字符型进行隐式转换转化为数字型
alert('您今年已经' + age + '岁啦~');
alert('下面是一个加法运算');
var num1 = prompt('请您输入第一个值:');
var num2 = prompt('请您输入第二个值:');
var result = parseFloat(num1) + parseFloat(num2);
console.log(result);
alert('您的结果是:' + result);
alert('下面是输出的结果:' + '\n' + '您的年龄是:' + age + '\n' + '您的结果是:' + result);
</script>
<body>
</body>
</html>