求数组的最大值与最小值
Math.min(...array)
Math.max(...array)
过滤错误值
const array = [1, 0, undefined, 6, 7, '', false];
array.filter(Boolean);
判断简化
if(a === undefined || a === 10 || a=== 15 || a === null) {
}
if([undefined, 10, 15, null].includes(a)) {
}
清空数组
let array = ["A", "B", "C", "D", "E", "F"]
array.length = 0
console.log(array)
对象(数组)验证方式
parent?.child?.child1?.child2
const array = [1, 2, 3];
array?.[5]
优化if/else
const onButtonClick = (status, identity) => {
if (identity == 'guest') {
if (status == 1) {
} else if (status == 2) {
} else if (status == 3) {
} else if (status == 4) {
} else if (status == 5) {
} else {
}
} else if (identity == 'master') {
if (status == 1) {
} else if (status == 2) {
} else if (status == 3) {
} else if (status == 4) {
} else if (status == 5) {
} else {
}
}
}
const functionA = ()=>{}
const functionB = ()=>{}
const functionC = ()=>{}
const actions = new Map([
['guest_1', () => { functionA }],
['guest_2', () => { functionB }],
['guest_3', () => { functionC }],
['guest_4', () => { functionA }],
['default', () => { functionC }],
])
const onButtonClick = (identity, status) => {
let action = actions.get(`${identity}_${status}`) || actions.get('default')
action.call(this)
}
有条件的对象属性
nst getUser = (emailIncluded) => {
return {
name: 'John',
surname: 'Doe',
...emailIncluded && { email : 'john@doe.com' }
}
}
const user = getUser(true);
console.log(user);
const userWithoutEmail = getUser(false);
console.log(userWithoutEmail);
传参最好传对象,不要传数组
解构对象技巧
const {a,b,c,d,e} = obj || {};
关于if中判断条件
if(
type == 1 ||
type == 2 ||
type == 3 ||
type == 4 ||
){
}
const condition = [1,2,3,4];
if( condition.includes(type) ){
}
关于输入框非空的判断
if(value !== null && value !== undefined && value !== ''){
}
if((value??'') !== ''){
}