💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] # 4.1 强制转换 ## 4.1.1 boolean ~~~ var a = "hello"; var b = 20; console.log(Boolean(a)); //true console.log(Boolean(b)); //true ~~~ > == 特殊 ~~~ console.log(""==0); //true console.log(undefined == null); //true ~~~ ~~~ other-->boolean Boolean(); 就这五种情况为false ""(中间没有空格),0,NaN,undefined,null-->false ~~~ ## 4.1.2 Number ~~~ string,boolean-->Number(value) 特点:只能识别纯数字的字符串 true-->1 false-->0 ~~~ ~~~ var a = "12"; var b = "true"; var c = true; var d = false; var e = "12px" console.log(Number(a)); //12 console.log(Number(b)); //NaN console.log(Number(c)); //1 console.log(Number(d)); //0 console.log(a-b); //NaN ~~~ ## 4.1.3 string * string-->number; ~~~ parseInt(); parseFloat(); ~~~ > Tip:第一位必须为数字 ~~~ var test = document.getElementById("test"); var height = test.style.height; console.log(parseInt(height)); test.onclick = function(){ this.style.height = parseInt(this.style.height)+1+"px"; //点击一下高度加1 } var a="12px"; var b = "a13px"; var c = "13.45px"; console.log(parseInt(a)); //12 console.log(parseInt(b)); //NaN console.log(parseInt(c)); //13 console.log(parseFloat(c)); //13.45 ~~~ ## 4.1.4 逻辑转换 ~~~ &&,||,! 结果返回boolean值 && 两边都为true,结果为true || 只要一遍为true,结果为true !-->取反 var a = 10; var b = 20; var c = 30; var d = 40; console.log(a<b && c>d); console.log(a<b && c<d); console.log(a<b || c>d); console.log(!(a>b)) ~~~ ## 4.1.4 总结 ~~~ other-->Number Number(value) string--Number parseInt(),parseFloat() other-->Boolean Boolean() other--String String() toString() var a = 20; var b = true; console.log(String(a)); //20 console.log(b.toString()); //true ~~~ # 4.2 自动转换 ~~~ 自动转换发生在计算中 算术,比较,逻辑,三目,赋值 == 1.只要一边为boolean,先将其转为number 2.一边为string,一边为number,先将string-->number 3.NaN和任何值运算,结果都为false 1.变量 2.数据类型的分类 3.运算符和表达式 4.数据类型转换 ~~~