工作中见到的js简写字符总结如下:
1、|| 和 ??
// || 使用
function(obj){
var a = obj || {}
}
// 等价于
function(obj){
var a;
if(
obj === 0 ||
obj === "" ||
obj === false ||
obj === null ||
obj === undefined
){
a = {}
} else {
a = obj;
}
}
// ?? 使用 (比 || 可以使用 0,"", false 都是有效值)
function(obj){
var a = obj ?? {}
}
// 等价于
function(obj){
var a;
if(
obj === null ||
obj === undefined
){
a = {}
} else {
a = obj;
}
}
2、~ 和 indexOf 、includes
const a = '123123';
if(!~a.indexOf('4')){
console.log('不存在')
}else{
console.log('存在')
};
Boolean(-1); 不存在
// true
Boolean(~-1); 不存在
// false
Boolean(~0); 存在
// true
const str = '123123123123'
str.includes('') // true
str.includes('2') // true
str.includes(2) // true
str.includes(5) // false
const arr = [1,24,3]
arr.includes('1'); // false
arr.includes(1); // true
arr.includes(5); // false
3、+new Date()
+new Date(); // 1618295521882
// +new Date() 会调用Date.prototype 上面的 valueOf方法,根据
new Date().getTime() === new Date().valueOf() //true
+new Date(); // 精确到毫秒
new Date().getTime(); // 精确到毫秒
new Date().valueOf(); // 精确到毫秒
new Date()*1; // 精确到毫秒
Date.now(); // 精确到毫秒
Date.parse(new Date()); //1603009257000,精确到秒
4、new Set() 去重
const numbers = [1,2,3,2,2,4];
const uniqueNumbers = [...new Set(numbers)]; // [1,2,3,4]
5、!! 转化 Boolean
!!true // true
!!2 // true
!![] // true
!!'str' // true
!!0 // false
!!'' // false
!!false // false
6、...传播结构
const student = {
name:'lxq',
age: 30,
city:'BeiJing',
state:'Success',
}
const {name,age, ...address} = student;
7、Object.keys、Object.values
const student = {
name:'lxq',
age: 30,
city:'BeiJing',
state:'Success',
}
Object.keys(student);
Object.values(student);
8、includes
let num = 2;
// bad
if(num == 1 || num == 2 || num == 3){
console.log('Yay');
}
// good
const checkArr = [1,2,3];
if(checkArr.includes(num)){
console.log('Yay');
}
9、**
Math.pow(4,2) // 16
Math.pow(2,3) // 8
4**2 // 16
4**3 // 64
2**3 // 8
2**4 // 16
10、~~和 Math.floor
Math.floor(5.256); // 5
~~5.256; // 5
后面碰到新的用法,再更新💻!