以下代码旨在从单词列表构建一个对象。
var buildDictionary = function() {
console.log("Buildling Dictionary");
console.log(masterList);
var word, vowelString, dict = {};
for (var i = 0; i < masterList.length; i++) {
word = masterList[i][0];
vowelString = getVowels(masterList[i]);
console.log(vowelString);
if (dict[vowelString] == undefined)
dict[vowelString] = [word];
else
dict[vowelString].push(word);
}
return dict;
}
var dictionary = buildDictionary();
按原样运行时,字典是一个空对象。但是,如果我手动调用它...
dictionary = buildDictionary();
它按预期工作!
完整的代码(如果相关)可在此处获取 https://jsfiddle.net/4yts4uvr/
最佳答案
在你的jsfiddle中,masterList是使用ajax加载的,你需要在回调中构建你的字典。
$.ajax({
type: "GET",
url: "../data/cmudict-0.7b"
}).success(function(content) {
// do stuff with content
}).then(function() {
// make your second ajax call (or look at jQuery.when)
$.ajax({
type: "GET",
url: "../data/cmudict-0.7b.phones"
}).success(function(content) {
// do stuff with content
}).then(function() {
var dictionary = buildDictionary();
});
});
这样您就可以确保在运行 buildDictionary 函数之前拥有所需的所有数据。
您可以执行同步 http 请求(阻塞),但是在主线程上执行时它们已被弃用:
Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
关于javascript - JavaScript 中的函数行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29374517/