17个JavaScript简洁代码技巧,让代码纵享丝滑

alt

1. ? 替换 if...else 语句

const age = 12;
let adultOrChild;

if (age >= 18) {
    adultOrChild = 'Adult';
else {
    adultOrChild = 'Child';
}

// 简写
adultOrChild = age >= 18 ? 'Adult' : 'Child';

/**
 * 函数的情况
 */
if (age >= 18) {
    doAdultThing();
else {
    doChildThing();
}

// 简写
(age >= 18 ? doAdultThing : doChildThing)();

2. && 短路替换 if 语句

const age = 18;
let adultOrChild;
if (age >= 18) {
    adultOrChild = 'Adult';
}

// 简写
age >= 18 && (adultOrChild = 'Adult');

3. includes 压缩多个 if 语句

const num = 3;

if (num === 1 || num === 2 || num === 3) {
    console.log('OK');
}

// 简写
if ([1, 2, 3].includes(num)) {
    console.log('OK');
}
// 还可以用&&进一步简写
[1, 2, 3].includes(num) && console.log('OK');

4. 使用对象替换 if...else...if 语句

const name = 'Tom';
let judge = '';
if (name = 'Jack') {
    judge = 'good';
else if (name = 'John') {
    judge = 'normal';
else if (name = 'Tom') {
    judge = 'bad';
}

// 简写
const judgeObj = {
    Jack: 'good',
    John: 'normal',
    Tom: 'bad'
}
let judge = judgeObj[name];

5. ** 指数运算

Math.pow(6, 3); // 216

// 简写
6 ** 3; // 216

6. ~~ 实现向下取整

Math.floor(6.3); // 6

// 简写
~~6.3 // 6

7. !! 把值转为布尔类型

!!'test' // true
!!true // true
!!3 // true
!![] // true

8. 使用+把字符串转化为数字

Number('89') // 89
+'89' // 89
// 如果字符串含有非数字字符,则会变成NaN
+'3A96' // NaN

9. ?. 防崩溃处理

const person = {
    
    
    name: 'Jack',
    age: 18,
    otherInfo: {
        height: 178
    }
}

console.log(person && person.otherInfo && person.otherInfo.height);

// 简写
console.log(person?.otherInfo?.height); // ?.是ES11里的内容,目前Chrome浏览器控制台不支持

10. 使用??判断 null 与 undefined

const count = 0; // 当count为null和undefined时打印 - ,其他情况打印count
if (count === null || count === undefined) {
    console.log('-');
else {
    console.log(count);
}

// 简写
console.log(count ?? '-');

11. 使用扩展运算符...

// 复制数组的场景
const arr = [1, 2, 3, 4];
const copyArr1 = arr.slice();
const copyArr2 = [...arr];

// 合并数组的场景
const newArr = [5, 6, 7, 8];
const mergeArr1 = arr.concat(newArr);
const mergeArr2 = [...arr, ...newArr];

// 同样适用于对象
const person = {
    name: 'Jack',
    age: 18
}
const newPerson = { ...person, height: 180 }

12. 使用 Set 给数组去重

const arr = [1, 1, 2, 3, 4, 4];
const uniqueArr = [...new Set(arr)];

13. 用一行代码给多个变量赋值

let a, b, c, d;
a = 1;
b = 2;
c = 3;
d = 4;

// 简写
let a = 1, b = 2, c = 3, d = 4;
// 或者使用解构赋值
[a, b, c, d] = [1, 2, 3, 4];

解构赋值用于 js 对象:

let student = {
    
    
    name: 'Jack',
    age: 18
}
let name = student.name;
let age = student.age;

// 简写
let { name, age } = student;

14. 交换两个变量的值

let x = 1;
let y = 2;

let temp = x;
x = y;
y = temp;

// 简写
[x, y] = [y, x];

15. 使用 Array.find()从数组中查找特定元素

const personList = [
    { name: 'Jack', age: 16 },
    { name: 'Tom', age: 18 },
]
let JackObj = {};
for (let i = 0, len = personList.length; i < len; i++) {
    if (personList[i].name === 'Jack') {
        JackObj = personList[i];
    }
}

// 简写
JackObj = personList.find(person => person.name === 'Jack');

16. 使用 Array.some()检测数组是否有元素满足指定条件

const personList = [
    { name: 'Jack', age: 16 },
    { name: 'Lily', age: 18 }
]
let hasAdult = false;
personList.forEach(item => {
    item.age >= 18 && (hasAdult = true);
})

// 简写
hasAdult = personList.some(item => item.age >= 18);

17. 同名对象属性简写

const name = 'Jack',
    age = 18;

const personObj = {
    name: name,
    age: age
}

// 简写
const personObj = {
    name,
    age
}

本文由 mdnice 多平台发布

猜你喜欢

转载自blog.csdn.net/ppppppppppsd/article/details/128705479