微信扫一扫看面试题

关注面试题库

我的前端代码简洁之道 (大神必备)

 1.通过条件判断给变量赋值布尔值的正确姿势

// bad
if (a === 'a') {
    b = true
} else {
    b = false
}

// good
b = a === 'a'

2.在if中判断数组长度不为零的正确姿势

// bad
if (arr.length !== 0) {
    // todo
}

// good
if (arr.length) {
    // todo
}

3.同理,在if中判断数组长度为零的正确姿势

// bad
if (arr.length === 0) {
    // todo
}

// good
if (!arr.length) {
    // todo
}

4.简单的if判断使用三元表达式

// bad
if (a === 'a') {
    b = a
} else {
    b = c
}

// good
b = a === 'a' ? a : c

5.使用includes简化if判断

// bad
if (a === 1 || a === 2 || a === 3 || a === 4) {
    // todo
}

// good
let arr = [1, 2, 3, 4]
if (arr.includes(a)) {
    // todo
}

巧用数组方法,尽量避免用for循环

6.使用some方法判断是否有满足条件的元素

// bad
let arr = [1, 3, 5, 7]
function isHasNum (n) {
    for (let i = 0; i < arr.length; i ++) {
        if (arr[i] === n) {
            return true
        }
    }
    return false
}

// good
let arr = [1, 3, 5, 7]
let isHasNum = n => arr.some(num => num === n)

// best
let arr = [1, 3, 5, 7]
let isHasNum = (n, arr) => arr.some(num => num === n)

7.使用forEach方法遍历数组,不形成新数组

// bad
for (let i = 0; i < arr.length; i ++) {
    // todo
    arr[i].key = balabala
}

// good
arr.forEach(item => {
    // todo
    item.key = balabala
})

8.使用filter方法过滤原数组,形成新数组

// bad
let arr = [1, 3, 5, 7],
    newArr = []
for (let i = 0; i < arr.length; i ++) {
    if (arr[i] > 4) {
        newArr.push(arr[i])
    }
}

// good
let arr = [1, 3, 5, 7]
let newArr = arr.filter(n => n > 4) // [5, 7]

9.使用map对数组中所有元素批量处理,形成新数组

// bad
let arr = [1, 3, 5, 7],   
    newArr = []
for (let i = 0; i < arr.length; i ++) {   
    newArr.push(arr[i] + 1)
}

// good
let arr = [1, 3, 5, 7]
let newArr = arr.map(n => n + 1) // [2, 4, 6, 8]

巧用对象方法,避免使用for...in

10.使用Object.values快速获取对象键值

let obj = {  
    a: 1,  
    b: 2
}
// bad
let values = []
for (key in obj) {  
    values.push(obj[key])
}

// good
let values = Object.values(obj) // [1, 2]

11.使用Object.keys快速获取对象键名

let obj = {   
    a: 1,   
    b: 2
}
// bad
let keys = []
for (value in obj) {  
    keys.push(value)
}

// good
let keys = Object.keys(obj) // ['a', 'b']

巧用解构简化代码

12.解构数组进行变量值的替换

// bad
let a = 1,  
    b = 2
let temp = a
a = b
b = temp

// good
let a = 1,  
    b = 2
[b, a] = [a, b]

13.解构对象

// bad
setForm (person) {  
    this.name = person.name   
    this.age = person.age
}

// good
setForm ({name, age}) {  
    this.name = name  
    this.age = age 
}

14.解构时重命名简化命名

有的后端返回的键名特别长,你可以这样干

// bad
setForm (data) {   
    this.one = data.aaa_bbb_ccc_ddd   
    this.two = data.eee_fff_ggg
}
// good
setForm ({aaa_bbb_ccc_ddd, eee_fff_ggg}) {  
    this.one = aaa_bbb_ccc_ddd  
    this.two = eee_fff_ggg
}

// best
setForm ({aaa_bbb_ccc_ddd: one, eee_fff_ggg: two}) {  
    this.one = one   
    this.two = two
}

15.解构时设置默认值

// bad
setForm ({name, age}) {  
    if (!age) age = 16   
    this.name = name  
    this.age = age 
}

// good
setForm ({name, age = 16}) {  
    this.name = name   
    this.age = age
}

16.||短路符设置默认值

let person = {   
    name: '张三',  
    age: 38
}

let name = person.name || '佚名'

17.&&短路符判断依赖的键是否存在防止报错'xxx of undfined'

let person = {   
    name: '张三',  
    age: 38,  
    children: {     
        name: '张小三'  
    }
}

let childrenName = person.children && person.childre.name

18.字符串拼接使用${}

let person = {  
    name: 'LiMing',   
    age: 18
}
// bad
function sayHi (obj) {  
    console.log('大家好,我叫' + person.name = ',我今年' + person.age + '了')
}

// good
function sayHi (person) {  
    console.log(`大家好,我叫${person.name},我今年${person.age}了`)
}

// best
function sayHi ({name, age}) {   
    console.log(`大家好,我叫${name},我今年${age}了`)
}

19.函数使用箭头函数

let arr [18, 19, 20, 21, 22]
// bad
function findStudentByAge (arr, age) {  
    return arr.filter(function (num) {    
        return num === age   
    })
}

// good
let findStudentByAge = (arr, age)=> arr.filter(num => num === age)

20.函数参数校验

// bad
let findStudentByAge = (arr, age) => {
    if (!age) throw new Error('参数不能为空')
    return arr.filter(num => num === age)
}

// good
let checkoutType = () => {
    throw new Error('参数不能为空')
}
let findStudentByAge = (arr, age = checkoutType()) =>
    arr.filter(num => num === age)

21.如果你的代码有很多 if ... else ...结构

如果你的代码有很多 if ... else ...结构,你不知道怎么优化,你就应该使用表驱动编程。

善用map哈希表的数据结构,js对象也就是字典,设置obj={key:value},通过obj[key]取出值,代替if..else..或者switch..case..等逻辑

优化前:howManyDays(year, month){
    if(month === 1 ||
        month === 3 ||
        month === 5 ||
        month === 7 ||
        month === 8 ||
        month === 10 ||
        month === 12
    ){
        return 31
    }else if(month === 2){
        return isLeapYear(year) ? 29 : 28
    }else{
        return 30
    }
}优化后:howManyDays(year, month){
    const table = {
        1: 31, 3: 31, 5: 31, 7: 31, 8: 31, 10: 31, 12:31,
        4: 30, 6:30, 9: 30, 11: 30,
        2: isLeapYear(year) ? 29 : 28
    }
    return table[month]
优化前:function calculateGrade(score){    if(score>=90){
        return 'A'
    }else if(score >= 80){
        return 'B'
    }else if(score >= 70){
        return 'C'
    }else if(score >= 60){
        return 'D'
    }else {
        return 'E'
    }
}优化后:function calculateGrade(score){
    const table = {
        100: 'A', 
        90: 'A',
        80: 'B',
        70: 'C',
        60: 'D',
        others: 'E'
    }
    return table[Math.floor(score/10)*10] || table['others']
}

22 用多态来代替条件语句

// bad
if (type === 'text') {
    // do something
} else if (type === 'select') {
    // do something else
}




个人写这种代码的一种常用方式是:
const control = {
    text: {
        mapper() {},
        restore(){},
        name: 'this is a text field',
    },
    select: {
        mapper() {},
        restore(){},
        name: 'this is a select field',
    }
}


control[type].mapper();

38a39975aca20ae132d029218c3a3528.png

posted @ 2022-07-23 10:02  web前端面试小助手  阅读(106)  评论(0)    收藏  举报