【问题标题】:I can console.log my array but it's values shows up as undefined when appended to a div我可以 console.log 我的数组,但它的值在附加到 div 时显示为未定义
【发布时间】:2016-09-15 00:11:11
【问题描述】:

我可以在单步执行数组以构建列表项之前和之后对数组进行控制台记录。当我运行代码时,我在我的 html 中得到了 10 个列表项,它们都读取为“未定义”,而不是我从 chrome 历史记录中提取的值。

有什么想法吗?

var urlarray = []

var historyResults = function () {

var microsecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
var oneWeekAgo = (new Date).getTime() - microsecondsPerWeek;

chrome.history.search({
    'text': '',            // Return every history item....
    'startTime': oneWeekAgo  // that was accessed less than one week ago.
}, function(historyItems) {
    for (var i = 0; i < historyItems.length; ++i) {
        urlarray.push(historyItems[i].url);
}
})
console.log(urlarray)

}

historyResults()


function addElement () { 

var makeUL = function(data) {

var ul = document.createElement("ul");
// create the UL 

console.log(urlarray)

for (i = 0; i < 10; i++) {
var a = document.createElement('a');
    a.href = data[i];
    a.appendChild(document.createTextNode(data[i]));
    console.log(a)
var li = document.createElement("li");
  li.appendChild(a);
ul.appendChild(li);
// step through the array and create a link out of the value of the array and append them to the list item
// append the list item to the UL
}

return ul;
// return ul full of li
}

console.log(urlarray)
document.getElementById("arraylist").appendChild(makeUL(urlarray));
// go to html to find div and append the full UL with urlarray as the array
}

addElement()

【问题讨论】:

    标签: javascript html arrays


    【解决方案1】:

    您遇到了两个问题。

    首先,您正在记录数组,但您的浏览器并没有立即记录它。当它有可用的 CPU 时,它会这样做。当您记录数组时,它尚未填充值。片刻之后,当您在浏览器控制台中展开数组时,数组现在已被填充,因为数组的计算被延迟了

    如果您将日志语句更改为:console.log(JSON.stringify(urlarray)),您可以更清楚地看到这一点。这会强制立即评估对象并将其转换为 JSON 字符串,稍后可将其写入浏览器控制台。

    有关记录对象延迟评估的更多信息,请参阅this question

    好的,这将我们带到您的第二个问题。您的日志记录语句在对 chrome.history.search 的回调之前执行。这就是数组尚未填充的原因。您需要使用 Promise 来确保您的代码按预期顺序执行。为此,您应该使用 jQuery 或 Q 之类的库。

    我建议阅读有关承诺的内容。无论您使用哪个库,您的代码都将遵循以下基本结构:

    1. 获取“延迟”对象。我就叫它deferred
    2. 在您的回调中,使用数组解析deferreddeferred.resolve(urlarray)
    3. 在您的日志记录语句所在的位置,从延迟对象中获取承诺。从 historyResults 方法返回该承诺。
    4. 在您调用 historyResults 的地方,改为:
    historyResults.then(function(urls) { 
        console.log("promise was resolved!", urls);
        // do things with your urls here, like add elements
    });
    

    在此回调中执行依赖于您的网址的操作此处。如果这样做,您的代码将保证在 urls 数组完全填充并准备就绪时执行。

    这是一个很大的话题,所以谷歌“javascript promises”,祝你好运。我希望这有助于您朝着正确的方向开始。

    如果您不想使用承诺:

    如果您不想使用 Promise,则需要在对 chrome.history.search 的回调中执行所有操作。这是保证数组被填充的唯一方法。

    异步代码很有趣。

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2012-01-25
      • 2015-07-10
      • 1970-01-01
      相关资源
      最近更新 更多