前端提高优雅代码的一些知识点

122 阅读1分钟

前端常用到的一些简写知识点

可选链

const student = {
  name: "mickey",
  age: 18,
  address: {
    city: "YanTai"
  },
};
 
// 使用 &&
console.log(student && student.address && student.address.Area); // 不存在返回 undefined
 
// 使用 ?.
console.log(student?.address?.Area); // 不存在返回 undefined

转换为布尔值

!!true    // true
!!2       // true
!![]      // true
!!"Test"  // true
 
!!false   // false
!!0       // false
!!""      // false

Boolean(true)   // true
Boolean(2)      // true
Boolean("Test") //true
...

检查多条件

const num = 1;
 
// 使用 ||
if(num == 1 || num == 2 || num == 3){
  console.log("Wow");
}
 
// 使用 includes()
if([1,2,3].includes(num)){
  console.log("Wow");
}

数字求幂 运算符

// 使用 Math.pow()
Math.pow(4,2); // 16
Math.pow(2,3); // 8
 
// 使用 **
4**2 // 16
2**3 // 8

字符串转数值

// 使用 parseInt()
parseInt(1.22)       // -> 1
// 使用 parseFloat()
parseFloat('1.2222') // -> 1.2222
// 使用Number()
Number('1.11')      // -> 1.11
//使用 + 
+'1.11'          // -> 1.11

向下取整数值

// 使用 Math.floor
Math.floor(5.25) // -> 5.0
 
// 使用 ~~
~~5.25   // -> 5.0

向上取整数值

// 使用 Math.ceil
Math.ceil(5.25) // -> 6.0

四舍五入取整数值

// 使用 Math.round
Math.round(5.49) // -> 5.0