[轉] JS運算子 &&和|| 及其優先順序

來源:互聯網
上載者:User

標籤:console   var   解析   als   優先   邏輯   優先順序   str   false   

第一、&& (邏輯與)運算,看一個簡單的例子:

var a = 1 && 2 && 3;
var b = 0 && 1 && 2;
var c = 1 && 0 && 2;
console.log(a);//值為3
console.log(b);//值為0
console.log(c);//值為0

啟動並執行結果是 :3,0,0。

解析:

“&&” 運算遇到false就返回;

變數a的計算:因為1 && 2,1為真,返回2;2&&3, 2為真,返回3 。

變數b的計算:因為0 && 1,0為假,返回0,不再往下計算。

第二、|| (邏輯或)運算,看一個簡單的例子:

var d = 0 || 1 || 2;
var e = 1 || 0 || 2;
var f = 1 || 2 || 0;

console.log(d);//值為1
console.log(e);//值為1
console.log(f);//值為1

 解析:

“||”運算遇到true就返回;

變數d的計算:因為0 || 1,0為假,返回1;1 || 2, 1為真,返回1 。

變數e的計算:因為1 || 0,1為真,返回1,不再往下計算。

三、&& (邏輯與) 和||(邏輯或)混合使用:

var g =  1 && 2 || 3;

var h = 1 || 2 && 3;

var i = 0 || 2 && 3;

console.log(g);//值為2
console.log(h);//值為1 

console.log(h);//值為3

 解析:

&& (邏輯與) 優先順序高於||(邏輯或);

變數g的計算:因為1 && 2,1為真,返回2;2 || 3, 2為真,返回2 。

變數e的計算:等式看成 1 || (一個值),1為真,最終直接返回1,不需要計算後邊的等式的值。

變數i的計算:因為2 && 3,2為真,返回3;0 || 3,0為假,返回3。

 

[轉] JS運算子 &&和|| 及其優先順序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.