javascript - JavaScript 中的函数行为不一致

标签 javascript function

以下代码旨在从单词列表构建一个对象。

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/

相关文章:

javascript - 在 Javascript 中创建一个包含树元素的数组

c++ - 如何在 C++ 中定义匿名函数?

javascript - 多个加载 GIF 并加载多个 PHP 页面

javascript - 不变违规 : View config getter callback for component `RNCSafeAreaProvider` must be a function (received `undefined` )

javascript - 将一个多维数组 append 到另​​一个多维数组javascript的底部

javascript - 翻译/本地化/国际化静态页面和单页应用程序

javascript - For 循环不会按原始顺序附加到其他 json

c - 在Emacs中进行C开发时如何跳转到函数?

java - Java中的函数指针数组

javascript - 重定向后运行一次函数