我正在从“学习jQuery”一书中学习jQuery,并发现部分代码无法理解。
有一部分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'])
P.S。我试图搜索stackoverflow和谷歌,但无法找到解释。
答案 0 :(得分:2)
您的JSON结构具有可选键quote
。
如果密钥存在,entry['key']
在布尔上下文(if
)中求值为true。如果它不存在,则计算结果为false,并且不执行后续的if-block。
所以,总结一下:
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"]);
答案 1 :(得分:2)
所有if(entry ['quote'])正在检查输入结构中是否存在此键。
答案 2 :(得分:0)
entry
只是$.each
引用的匿名函数中的第二个参数。 ['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?"]