数据类型转换
<body>
<script>
console.log(parseInt('123.1a'))
console.log(parseFloat('123.1a'))
console.log(Number(true))
console.log(Number(false))
console.log(Number(undefined))
console.log(Number(null))
</script>
</body>
NaN是number类型中一个特殊值,不是数字,如果你的运算得不到一个数字,此时就会得到NaN。NaN表示错误的运算。 产生的原因一般是代码出bug。NaN不能参与任何运算,结果一律是NaN。
<body>
<script>
console.log(String(123))
let num = 255
console.log(num.toString(16))
</script>
</body>
变量名.toString(),如果是undefined与null,这种方式会报错。这种方式支持进制转换,例如把十进制转十六进制。
<body>
<script>
console.log(Boolean(0))
console.log(Boolean(-0))
console.log(Boolean(NaN))
console.log(Boolean(null))
console.log(Boolean(undefined))
console.log(Boolean(false))
console.log(Boolean(''))
</script>
</body>
7种数据会得到false,除false7种之外的一切数据是true。注意''和' ',空字符串和空格字符串,空字符串是false,空格字符串是true。
隐式转换
<body>
<script>
console.log('10' - 1)
console.log(1 + true)
console.log(+'10')
console.log('1' + true)
console.log(!1)
console.log(!null)
</script>
</body>
当运算符两边的 ‘数据类型不一致’ 的时候,编译器会转成一致后运算。 (1)转换数字 : 算术运算符 + - * / % (2)转换字符串 : 连接符+ (+号两边只要有一边是字符串,此时+就是连接符) (3)转换布尔: 逻辑非 !
undefined与null
<body>
<script>
console.log(undefined == null)
console.log(Boolean(undefined))
console.log(Boolean(null))
console.log(undefined === null)
console.log(Number(undefined))
console.log(Number(null)
</script>
</body>
undefined : 未定义。 当变量只声明,但是没有赋值,此时默认值是undefined。 null : 有定义,定义的值是空值。
三元表达式
<body>
<script>
let res = 1 > 0 ? 10 : 20
document.write(res)
</script>
</body>
运算符根据运算数的多少,分为一元、二元、三元运算符
一元运算符:只能运算一个数 ++ -- !
二元运算符:能运算两个数 算术、比较
三元运算符: 能运算三个数 表达式 ? 代码1 : 代码2
执行规则: 如果表达式为true,则执行代码1,否则执行代码2
如果你的代码只有1行,则可以用三元,如果有多行,建议使用if-else语句。