一.进行相关类型的转换
1.变为数字型
<script>
var a = prompt("请输入");
console.log(parseInt(a));
console.log(parseInt("3.3333"));
console.log(parseFloat('3.33'));
var char1 = '123';
console.log(Number(char1));
console.log('14' - 0);
console.log('111' * 1);
</script>
2.变为字符串型
<script>
var c = 10;
console.log(c.toString());
console.log(String(10));
var b = 10 + '';
console.log(b);
</script>
结果:
3.转为bool类型
<script>
console.log(Boolean(''));
console.log(Boolean(0));
console.log(Boolean(NaN));
console.log(Boolean(undefined));
console.log(Boolean(null));
console.log('——————————————————');
console.log(Boolean('11'));
console.log(Boolean(100));
console.log(Boolean('?'));
</script>
结果:
案例实践:
用类型转换得到18位身份证的出生日期: 代码:
<script>
var IdCard = prompt("请输入");
var year = IdCard.slice(6, 10);
var month = IdCard.slice(10, 12);
var day = IdCard.slice(12, 14);
console.log(parseInt(year));
console.log(parseInt(month));
console.log(parseInt(day));
</script>
结果:
二.js的运算符
js有许多运算符跟c/c++一样,所以就说一下js中跟c语言中不一样的逻辑运算符 1.&&运算符
console.log(100 && 222);
console.log(0 && 222);
console.log(0 && 11 + 123 && 11);
console.log('' && 11 + 123 && 11);
console.log(123 && 11 + 123 && 11 + 11 && 1);
结果: 2. ||运算符
<script>
console.log(123 || 11);
console.log(0 || 11);
var a = 1;
console.log(123 || a++);
console.log(a);
</script>
结果: 逻辑运算符优先级
|