2011-12-17 44 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?"]