javascript中2個驚嘆號的用法執行個體詳解_javascript技巧

來源:互聯網
上載者:User

在javascript代碼中經常會見到!!的情況,本文即以執行個體形式較為深入的分析javascript中2個驚嘆號的用法。分享給大家供大家參考之用。具體分析如下:

javascript中的!!是邏輯"非非",即是在邏輯 NOT的基礎上再"非"一次。通過!或!!可以將很多類型轉換成bool類型,再做其它判斷。

一、應用情境:判斷一個對象是否存在

假設有這樣一個json對象:

{ color: "#E3E3E3", "font-weight": "bold" }

需要判斷是否存在,用!!再好不過。

如果僅僅列印對象,無法判斷是否存在:

var temp = { color: "#A60000", "font-weight": "bold" };alert(temp);

結果:[object: Object]

如果對json對象實施!或!!,就可以判斷該json對象是否存在:

var temp = { color: "#A60000", "font-weight": "bold" };alert(!temp);

結果:false

var temp = { color: "#A60000", "font-weight": "bold" };alert(!!temp);

結果:true

二、通過!或!!把各種類型轉換成bool類型的慣例

1.對null的"非"返回true

var temp = null;alert(temp); 

結果:null

var temp = null;alert(!temp); 

結果:true

var temp = null;alert(!!temp); 

結果:false

2.對undefined的"非"返回true

var temp;alert(temp);

結果:undefined

var temp;alert(!temp);

結果:true

var temp;alert(!!temp);

結果:false

3.對Null 字元串的"非"返回true

var temp="";alert(temp);

結果:空

var temp="";alert(!temp);

結果:true

var temp="";alert(!!temp);

結果:false

4.對非零整型的"非"返回false

var temp=1;alert(temp);

結果:1

var temp=1;alert(!temp);

結果:false

var temp=1;alert(!!temp);

結果:true

5.對0的"非"返回true

var temp = 0;alert(temp);

結果:0

var temp = 0;alert(!temp);

結果:true

var temp = 0;alert(!!temp);

結果:false

6.對字串的"非"返回false

var temp="ab";alert(temp);

結果:ab

var temp="ab";alert(!temp);

結果:false

var temp="ab";alert(!!temp);

結果:true

7.對數組的"非"返回false

var temp=[1,2];alert(temp);

結果:1,2

var temp=[1,2];alert(!temp);

結果:false

var temp=[1,2];alert(!!temp);

結果:true

相信本文所述對大家的javascript程式設計的學習有一定的借鑒價值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.