2011-12-17 46 views
1

我正在從書「Learning jQuery」中學習jQuery,並發現部分代碼不理解。在使用JSON時jQuery中if語句的解釋

有JSON的一部分:

[ 
    { 
     "term": "BACCHUS", 
     "part": "n.", 
     "definition": "A convenient deity invented by the...", 
     "quote": [ 
      "Is public worship, then, a sin,", 
      "That for devotions paid to Bacchus", 
      "The lictors dare to run us in,", 
      "And resolutely thump and whack us?" 
     ], 
     "author": "Jorace" 
    }, 
    { 
     "term": "BACKBITE", 
     "part": "v.t.", 
     "definition": "To speak of a man as you find him when..." 
    }, 
    { 
     "term": "BEARD", 
     "part": "n.", 
     "definition": "The hair that is commonly cut off by..." 
    }, 

這裏是jQuery代碼:

$(document).ready(function() { 
    $('#letter-b a').click(function() { 
     $.getJSON('b.json', function(data) { 
      $('#dictionary').empty(); 
      $.each(data, function(entryIndex, entry) { 
       var html = '<div class="entry">'; 
       html += '<h3 class="term">' + entry['term'] + '</h3>'; 
       html += '<div class="part">' + entry['part'] + '</div>'; 
       html += '<div class="definition">'; 
       html += entry['definition']; 
       if (entry['quote']) { 
        html += '<div class="quote">'; 
        $.each(entry['quote'], function(lineIndex, line) { 
         html += '<div class="quote-line">' + line + '</div>'; 

有人能解釋我的意思這行:

if (entry['quote']) 

附:我試圖搜索stackoverflow和谷歌,但無法找到解釋。

回答

2

所有如果(條目[「報價」])是做正在檢查該條目是否存在於條目結構中。

2

您的JSON結構有一個可選鍵quote

如果密鑰存在,entry['key']在布爾上下文中計算爲true(if)。如果它不存在,則評估爲false,並且後續的if塊不會被執行。

因此,要總結:

if (entry['quote']) {  // This block will only run if the JSON contains 
          // a key "quote" 
    html += '<div class="quote">'; 

如果你不確定的變量在布爾上下文中值,使用雙感嘆號(雙重否定),將其轉換爲一個布爾值:

alert("Quote exists? True or false: " + !!entry["quote"]); 
0

entry只是$.each引用的匿名函數中的第二個參數。的[「報價」]的部分是括號符號用於參考該特定屬性(即,),在這種情況下似乎是

"quote": [ 
"Is public worship, then, a sin,", 
"That for devotions paid to Bacchus", 
"The lictors dare to run us in,", 
"And resolutely thump and whack us?"]