toString() | 转换成字符串 | var num=1;alert(num.toString) |
String()强制转换 | 转换成字符串 | var num=1;alert(String(num)); |
加号拼接字符串 | 和字符串拼接的结果都是字符串 | var num=1;alert(num+'我是字符串'); |
<script>
//把数字转字符串
var num = 10;
var str = num.toString();
console.log(str);
console.log(typeof str);
</script>
<script>
//用这个方法也能实现数字转字符串
//console.log(String(num));
a = String(num);
console.log(a);
console.log(typeof a);
</script>
<script>
b = num + '';
console.log(b);
console.log(typeof b);
</script>

parseInt(string)函数 | 将string类型转换成整数数值型 | parseInt('10'); |
parseFloat(string)函数 | 将string类型转换成浮点数数值型 | parseFloat('2.5'); |
Number()强制转换函数 | 将String类型转换为数值型 | Number('12'); |
js隐式转换(- * /) | 利用算术运算隐式转换为数值型 | '10'-0 |
<script>
//parseInt();把字符串转换成数字,如果是小数,会自动舍弃小数取整
var age = prompt('请输入年龄');
a = parseInt(age);
console.log(a);
console.log(typeof a);
console.log(parseInt('100px'));
</script>


<script>
//parseFloat();把字符串转换成数字型,得到浮点数
console.log(parseFloat('3.5'));
</script>

<script>
//Number()强制转换
var num = '123';
console.log(Number(num));
</script>

<script>
//用算术运算符- * / 进行隐式转换
//不能用 + ,用了 + 就变成拼接字符串了
//两个字符串也能做运算
console.log('10' - 0);
console.log('12' * 1);
console.log('13' / 1);
console.log('14' + 0);
console.log('15' - '14');
console.log('16' - '17');
</script>

- 弹出一个输入框(prompt),让用户输入出生年份;
- 把用户输入的值保存起来,然后用今年的年份减去接收到的变量值
- 弹出警示框(alert),输出计算结果
<script>
a = prompt('请输入你的出生年份');
//本来a应该是字符串型,但是这里 - 有隐式转换,所以可以得到数字结果
alert(2020 - a);
//或 者这样写一样
alert(2020 - prompt('请输入你的出生年份'));
</script>

1.先用prompt弹出第一个输入框
2.再用prompt弹出第二个输入框
3.把得到的结果(字符串)转换成数字,并做加法运算
4.alert显示结果
<script>
a = prompt('请输入第一个数');
b = prompt('请输入第二个数');
res = parseFloat(a) + parseFloat(b)
alert('结果是:' + res);
</script>

方式 | 说明 | 案例 |
---|---|---|
Boolean()函数 | 其他类型转换成布尔值 | Boolean('true'); |
- 代表空、否定的值会被转换成false,如''、0 、NaN
<script>
//其他类型转换成布尔型
console.log(Boolean(''));
console.log(Boolean(0));
console.log(Boolean(NaN));
console.log(Boolean(null));
console.log(Boolean(undefined));
console.log('------------');
console.log(Boolean(123));
console.log(Boolean('啊好的乐山阿萨德佛'));
console.log(Boolean(12.3));
</script>

网友评论