JS || &&

來源:互聯網
上載者:User

標籤:答案   lag   sel   整數   對象   ase   var   nbsp   參考   

var a = 2;

var b = 3;

var andflag = a && b ;

var orflag = a || b;

問andflag 和orflag 分別是什嗎?

起初我認為: andflag 和orflag 的值都為 true; 畢竟 && 和 || 都是求Boolean ,後來發現,我錯了。

答案應該是  andflag  = 3,orflag = 2;

原因是這樣的:

在運算過程中,首先js  會將 && 和||  兩邊的值轉成Boolean 類型,然後再算值 ,&&運算如果返回true,則取後面的值,如果|| 返回true,則取前面的值 , 而其中數值轉換成boolean 的規則 是:

對象、非零整數、非Null 字元串返回true,

其它為false   ;

a && b  的運算就是  :因為  a  和  b全是非零整數,所以  a  和  b  也就是true ,而   true && true  返回   true   ,則取後面的b   ,同理  a 和b 全是非零整數,a  和b  全是true  ,則true || true  返回   true ,取|| 前面的值 也就是2;

 

同樣:該邏輯運算子支援短路原則:

如 var  a = “”  ||  null  || 3  ||  4   —->    var a = fasel || false || true ||  true  結果為true  則返回第一個true,即是3

var b = 4 && 5 && null && 0   ——>   var b = true && true && false && false   結果是false   則返回第一個false   即是null .

 

供自己參考!

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.