头图

链判断运算符

let arr = null;

if(arr?.length > 0){
  // '数组'
} else {
  // '非数组'
}

let a = arr?.length > 0;
// a = false
let list = [{ children: [] }, { children: [1,2,3] }]

// 先判断children存在才能调用length函数,否则报错,一般这么写
if(obj[0].children && obj[0].children.length > 0){
    console.log(obj[0].children)
} else {
    console.log(obj[1].children)
}

// 链判断简化写法
if(obj[0]?.children.length > 0){
    console.log(obj[0].children)
} else {
    console.log(obj[1].children)
}

Null运算符

某些情况下我们要判断值是否为null,你可能会使用 || 运算符

let exist = {
 num : 0,
 me : null
}
exist.num || '不存在' // '不存在'
exist.me || '不存在' // '不存在'

上述条件中两个判断都会返回不存在,实际上 num0 是需要返回 0 的, || 运算符存在隐式转换。
我们可以使用Null运算符: ??

exist.num ?? '不存在' // 0
exist.me ?? '不存在' // '不存在'

?? 运算符不存在隐式转换

注意:?? 运算符可以判断 nullundefined ,而NaN则判断为true

字符串补零

在操纵数字的时候,我们可能会判断该数字是否小于10,如果小于10则在前面补0

let month = 8;
let day = 7;
if(month < 10){
 month = `0${month}` // 08
}
if(day < 10){
 day = `0${day}` // 07
}

你可以使用padStart,判断字符串是否小于指定位数,否则补全指定字符

let month = 8;
let day = 7;
month = String(month).padStart(2,'0') // 08
day = String(day).padStart(2,'0') // 07

取数组最后一位

我们可能会这么写

let arr = [3,2,6,7,8]
arr[arr.length - 1] // 8

更简便的写法

let arr = [3,2,6,7,8]
arr.at(-1) // 8

三元表达式简化if判断

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

// good
b = a === 'a' ? true : false;

// best
b = a === 'a'

数组方法简化判断

当条件满足数组中的某个值时,进入业务逻辑,我们可以使用数组方法进行判断,避免冗长的if

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

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

箭头函数

关于箭头函数的详细说明以及注意点请看这篇文章: 箭头函数详解
这里只讨论箭头函数的this指向问题
箭头函数没有自己的this,箭头函数内部的this就是外层代码块的this

let obj = {
    name : 'DCodes',
    getArrow: () => {
       console.log(this)
    },
    getFn(){
        console.log(this)
    }
}

obj.getFn() // 传统函数指向的是上一级,也就是obj,因为是obj调用
obj.getArrow() // 箭头函数指向window,这也就说明箭头函数没有this,所以指向的是window

所以对象中不应该使用箭头函数
另外,需要动态this的时候,也不应该使用箭头函数

let button = document.getElementById('news')

button.addEventListener('click',()=>{
    this.classList.toggle('on')
})

button监听函数是一个箭头函数,导致内部的this是全局对象。如果改成普通函数,this就会动态指向被点击的按钮对象。
我们在自定义钩子函数,或需要动态this的时候千万不要使用箭头函数,否则会导致this指向失效,出现未知的错误。例如在vue2中,B函数就调用不到A函数。

export default {
    data() {},
    methods: {
        A: () => {
            console.log('箭头函数')
        },
        B() {
            this.A();
        },
    },
};

如果函数体很复杂,有许多行,或者函数内部有大量的读写操作,不单纯是为了计算值,这时也不应该使用箭头函数,而是要使用普通函数,这样可以提高代码可读性。


查看往期:
JavaScript 开发秘籍:日常总结与实战技巧-1


兔子先森
365 声望15 粉丝

致力于新技术的推广与优秀技术的普及。