1.if多条件判断
常规:
if(x===""abc"" || x==="def" || x===""ghi" || x ="jkl"){
}
优化:
if(['abc','def','ghi','jkl'].includes(x)){
}
2.函数条件调用
//常规
function test1(){
console.log('test1')
}
function test2(){
console.log('test2')
}
var test3 = 1;
if(test3==1){
test1()
}else{
test2()
}
//优化
(test3===1 ? test1:test2)();
可选链操作符(?.)
//常规
let data;
if(res && res.data && res.data.result && res.data.result[0]){
data = res.data.result
}
// 优化
let data =res?.data?.result?[0]
空值合并操作符号
//常规
if(first !==null || first !== undefined){
return first = ''
}
//优化
let test = frist ?? ''
声明多个变量
//常规
let x;
let y =20;
、、简写
let x ,y =20;
多个变量赋值
、、常规写法
let a,b,c
a=3;
b=4;
c=5
、、简写
let [a,b,c]=[3,4,5]
AND && 短路求值
//常规写法
if(isShow){
fun()
}
//简写
isShow && fun() //短路求值
交换两个变量的值
let [x,y]=['Hello','world'];
//常规 设置一个空容器去转换
let temp = x;
x=y;
y=temp
//简写
[x,y]=[y,x]
// 常规写法
function add(num1, num2) {
return num1 + num2;
}
// 简写
const add = (num1, num2) => num1 + num2;
// 常规写法
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// 执行一些代码
}
// 简写1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
// 执行一些代码
}
// 简写2
if ([1, 'one', 2, 'two'].includes(value)) {
// 执行一些代码
}
对象属性分配
let fristName = 'hello'
let lastName = 'world'
//常规写法
let obj = {firstName : fristNmae , lastName : lastName }
// 简写
let obj = { fristName , lastNAame }
字符串转数字
//常规
let total = parseInt('456');
let average = parseFloat('42.6')
//简写
let total = + '456';
lte averge = + '42.6'
(就是获取值前面拼接 + 号)
// 常规写法
let str = '';
for(let i = 0; i < 5; i ++) {
str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello
// 简写
'Hello '.repeat(5);
双NOT位运算符(~~)?
// 常规写法
const floor = Math.floor(6.8); // 6
// 简写
const floor = ~~6.8; // 6
找出数组中的最大最小值
const arr = [2, 8, 15, 4];
Math.max(...arr); // 最大值 15
Math.min(...arr); // 最小值 2
获取字符串中的某个字符
let str = 'jscurious.com';
// 常规写法
str.charAt(2); // c
// 简写
str[2]; // c
简化if else
let orderStatus;
let map={'1': '待付款', '2': '待发货', '3': '已发货', '4': '待收货','5':'已完成'}
orderStatus = map[res.data.status] res.data.status //后台返回校验值
console.log(orderStatus)
方法一
- 使用ES的最新语法:
Array.prototype.flat()
。 flat([dept])
,参数dept
为数组的深度,默认为1,根据传入的深度将数组展开。- 对于不确定深度的数组,可以传入
Infinity
(代表正无穷大)。
【示例】
ES10(2019)
Object.fromEntries():把键值对列表转换成一个对象
const arr = [
["a", "hello"],
["b", "world"],
];
console.log(Object.fromEntries(arr));//{a: 'hello', b: 'world'}
是和Object.entries()对应的操作
String.prototype.trimStart():删除字符串开头的空格
String.prototype.trimEnd() :删除字符串结尾的空格