关于多参数多条件的if...else如何优化?

多参数多条件的if...else如何优化?想把这两个函数优化成一个。

_chatMask: function () {
        wx.hideLoading();
        if (this.data.isLogin) {
            this.setData({
                dialogMask: true,
                chatMaskA: true,
            })
        };

        if (this.pureData.isSignIn && this.pureData.isChat && !this.pureData.isFollow) {
            this.setData({
                dialogMask: true,
                chatMaskB: true,
            })
            return
        };

        if (this.pureData.isShare && this.pureData.isChat && !this.pureData.isFollow) {
            this.setData({
                dialogMask: true,
                chatMaskC: true,
            })
            return
        };
    },

    _flockMask: function () {
        if (this.pureData.isSignIn && this.pureData.isFlock && !this.pureData.isFollow && !this.pureData.isExist) {
            this.setData({
                dialogMask: true,
                flockMaskA: true,
            })
            return
        };

        if (this.pureData.isSignIn && this.pureData.isFlock && this.pureData.isExist && !this.data.isEqual) {
            this.setData({
                dialogMask: true,
                flockMaskB: true
            })
            return
        };

        if (this.pureData.isShare && this.pureData.isFlock && !this.pureData.isFollow && !this.data.isEqual) {
            this.setData({
                dialogMask: true,
                flockMaskC: true,
            })
            return
        };
    },
阅读 1.8k
2 个回答
    _chatMask_flockMask: function () {
        wx.hideLoading();

        var i=this.pureData.isSignIn,
            s=this.pureData.isShare,
            c=this.pureData.isChat,
            f=this.pureData.isFollow,
            e=this.pureData.isExist,
            k=this.pureData.isFlock,
            q=this.data.isEqual;

        this.setData({
            dialogMask: true,

            chatMaskA: (this.data.isLogin),
            chatMaskB: (i && c && !f),
            chatMaskC: (s && c && !f),

            flockMaskA: (i && k && !f && !e),
            flockMaskB: (i && k &&  e && !q),
            flockMaskC: (s && k && !f && !q),
        })

    },

很容易就看出有重复条件判断,其实如果是多个标记且互斥唯一的话可以用枚举值,不需要那么多变量

this.setData({
    dialogMask: true,
    chatMaskA: isLogin,
    ['chatMask' + (isSignIn ? 'B' : isShare ? 'C' : '_')]: isChat && !isFollow,
    ['flockMask' + (isSignIn ? !isExist ? 'A' : 'B' : isShare && !isEqual ? 'C' : '_')] : isFlock && !isFollow
 })
推荐问题
宣传栏