发布于 

js的优化写法

记录下js的几种优秀写法

1
2
3
4
5
// 多条件判断的精简写法 
const options ['si','xue','tang'];
if (options.includes(value)){
return ;
}
1
2
3
4
5
6
// 如果条件不满足,则直接返回
function handleFun(event)
if (!event || !event.target){
return
}
}
1
2
// es6新增语法,可以避免null值无属性的报错
const value reponse?.data?.text // 链式运算符,无则返回undefined
1
2
// 取数组最后一位
const value = arr.at(-1)
1
2
3
4
// 判断赋值,如果foo为 null/undefined/0/false等用||,如果foo为null/undefined用??
// 具体见:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
const value = foo || bat
const value = foo ?? bat
1
2
// 三目运算符赋值
const value = a ? b : c
1
2
// 数组去重
const value = (arr)=> [... new Set(arr)]
1
2
3
//去除数组空项
let arr=[1,2,,4,5];
arr.flat(arr)
1
2
3
4
5
6
7
8
9
10
11
12
const a = 3;
const c = null

// a||c,输出第一个不为Falsy的值
// falsy有false、0、-0、0n、""、null、undefined 和 NaN
console.log(a || c);
// Expected output: 3

// a&&c,输出第一个不为Truthy的值
// 除 false、0、-0、0n、""、null、undefined 和 NaN 以外的皆为Truthy
console.log(a && c);
// Expected output: null