Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

妙用Javascript运算符“||”和“&&” #3

Closed
Wscats opened this issue Apr 15, 2016 · 0 comments
Closed

妙用Javascript运算符“||”和“&&” #3

Wscats opened this issue Apr 15, 2016 · 0 comments
Labels

Comments

@Wscats
Copy link
Owner

Wscats commented Apr 15, 2016

var a = 1;
        var b = 2;
        if (a < b && a == 1) {
            //console.log("&&");
        }
        //上面改写
        a < b && a == 1 && console.log("&&");
        if (a > b || a == 1) {
            //console.log("||");
        }
        //
        a > b || a == 1 && console.log("||");
        //&&前面为真运行后面 否则不运行
        var c = (a == 1) && 3
        var d = (a == 2) && 3
        console.log(c); //3     取了后面的3
        console.log(d); //false 取了前面的false
        //||前面为假运行后面 否则不运行
        var c = (a == 1) || 3
        var d = (a == 2) || 3
        console.log(c); //true
        console.log(d); //3
        //巧用
        var e = 0;
        var f;
        switch (f) {
            case 5:
                e = 1;
                break;
            case 10:
                e = 2;
                break;
            case 12:
                e = 3;
                break;
            case 15:
                e = 4;
                break;
            default:
                e = 0;
                break;
        }
        var e = (f == 5 && 1) || (f == 10 && 2) || (f == 12 && 3) || (f == 15 && 4) || 0;
        console.log(e); //0

总结理解为
&&遇上假就停止,并返回这个假,相反遇到真就继续执行直到拿最后一个
||遇上真就停止,并返回这个真,相反遇到假就继续执行直到拿最后一个
这样会不会好理解多
注意:非0的整数都为true,undefined、null和空字符串”" 为false。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant