我已经在这里待了一个小时,我需要帮助。这让我有点莫名其妙。考虑我的代码中对象的这种显式设置:
工作案例:
var terms={};
terms[0]={};
terms[1]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[2]={"label":"crayon","cell_src":"images/crayon.jpg","clue_type":"audio","clue_src":"/audio/car.wav"};
terms[3]={"label":"pen","cell_src":"images/pen.jpg","clue_type":"audio","clue_src":"/audio/car.wav"};
terms[4]={"label":"pencil","cell_src":"images/pencil.jpg","clue_src":"/audio/boat.wav"};
terms[5]={"label":"pencil_case","cell_src":"images/pencil_case.jpg","clue_src":"/audio/train.wav"};
terms[6]={"label":"rubber","cell_src":"images/rubber.jpg","clue_src":"/audio/taxi.wav"};
terms[7]={"label":"ruler","cell_src":"images/ruler.jpg","clue_src":"/audio/plane.wav"};
terms[8]={"label":"sharpener","cell_src":"images/sharpener.jpg","clue_src":"/audio/taxi.wav"};
window.terms= terms;
window.terms= terms; // for using globaly
如果我做一个 console.log(window.terms[1]); 我得到“包”。这就是我想要的。
不工作的情况
如果不是显式定义 term{} 的值,而是从 json 文件中读取内容并将它们分配给每个枚举索引,如下所示:
var terms={};
terms[0]={};
$.getJSON('content.json', function(data){
$.each(data,function(i){
//terms[i]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[i+1]={"label":data[i].headword,"cell_src":data[i].image,"clue_type":"audio","clue_src":data[i].audio};
});
window.terms=terms;
});
如果我做一个 console.log(window.terms[1]); 我收到一个错误“Uncaught TypeError: Cannot read property '1' of undefined”请注意,我有一个替代尝试注释掉了,我消除了我试图拉入的值出现奇怪的可能性,我明确分配所有索引都具有相同的静态值。这会产生相同的错误。
任何想法这怎么可能?