JavaScript类型转换
js的类型转换分为显式类型装换与隐式类型转换
- 显式类型转换
String()
将值转换为字符串类型变量.toString()
将变量转换为字符串型Number()
将值转换为数值型parseInt()
将值转换为整数,舍去小数部分parseFloat()
将值转换为小数(浮点数)
注意:
- 使用Number进行类型转换时,只要字符串中存在无法转换为数字的字符,就返回NaN
- 使用
parseInt()
与parseFloat()
进行类型转换时,会从前先后依次转换,遇到无法转换的字符则停止,只有第一个字符无法转换为数字时,才返回NaN
console.log(Number("123b")) // NaN
console.log(parseInt("123b")) // 123
console.log(parseFloat("123b")) // 123
- 隐式类型转换
-
当字符串与数值进行加法运算时,会自动将数值转换为字符串
console.log(12 + "jay"); // 12jay console.log("12" + "13"); // 1213,带引号的为字符串类型,因此结果为字符串拼接
-
当字符串与数值进行除加法以外的运算时,会自动将字符串转化为数字
console.log("123" - 12) // 111
-
根据以上隐式转换规则,我们可以这样进行运算:
console.log("12" / 1 + "13" / 1);
// 结果为25,对字符串进行除或乘使其隐式转换为数值型
console.log(12 + "" + 13)
// 结果为1213,加空字符串使其隐式转换为字符串
运算符
JS的运算符分为:
-
自增自减运算符(++ --)
// 常用于循环 i++; // 自增,等同于 i = i + 1;先进行运算,再加一 ++i; // 自增,等同于 i = i + 1;先加一,再进行运算 i--; // 自减,等同于 i = i - 1;先进行运算,再减一 --i; // 自减,等同于 i = i - 1;先减一,再进行运算
-
算术运算符(+ - * / %)
console.log(1 + 1); // 2 console.log("1" + "1"); // 11 字符串拼接 console.log(2 - 1); // 1 减法运算 console.log(2 * 2); // 4 乘法运算 console.log(4 / 2); // 2 除法运算 console.log(4 % 2); // 0 取余运算符,取4除以2的余数
-
关系运算符(> < >= <=)
// 关系运算符返回一个布尔值,满足关系则返回true,不满足关系返回false console.log(1 > 2); // false console.log(1 < 2); // true console.log(2 <= 2); // true console.log(3 >= 2); // true
-
逻辑运算符(&& || !)
// 逻辑运算符,返回一个布尔值 // &&(and)与运算符,运算符两侧所有条件为真时,返回真,一个条件为假则返回假 console.log(2 > 1 && 3 > 1); // true console.log(1 > 2 && 3 > 1); // false // ||(or)或运算符,运算符两侧条件有一个为真时,返回真,两个都为假时才为假 console.log(2 > 1 || 1 > 3); // true console.log(2 > 3 || 1 > 3); // false // !(not)非运算符,用于取反值,非真则为假,非假则为真 console.log(!true); // false console.log(!false); // true
-
赋值运算符(+= -= *= /= %=)
// += 加后赋值 i += 2; // 等同于 i = i + 2 i -= 2; // 等同于 i = i - 2 i *= 2; // 等同于 i = i * 2 i /= 2; // 等同于 i = i / 2 i %= 2; // 等同于 i = i % 2
运算符三要素
- 结合方向
- 优先级
- 操作目数