使用JSON时jQuery中if语句的说明
我正在学习《学习jQuery》一书中的jQuery,并发现部分代码不理解 JSON有一部分:使用JSON时jQuery中if语句的说明,jquery,if-statement,Jquery,If Statement,我正在学习《学习jQuery》一书中的jQuery,并发现部分代码不理解 JSON有一部分: [ { "term": "BACCHUS", "part": "n.", "definition": "A convenient deity invented by the...", "quote": [ "Is public worship, then, a sin,", "That
[
{
"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>';
另外,我试图搜索stackoverflow和Google,但找不到对此的解释。您的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">';
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">';
entry
只是$引用的匿名函数中的第二个参数。每个
。['quote']部分是用于引用特定属性(即键)的括号符号,在本例中,它似乎是
"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?"]
entry
只是$引用的匿名函数中的第二个参数。每个
。['quote']部分是用于引用特定属性(即键)的括号符号,在本例中,它似乎是
"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?"]
if(entry['quote'])所做的全部工作是检查条目结构中是否存在此键。if(entry['quote'])所做的全部工作是检查条目结构中是否存在此键