繁体   English   中英

我可以 console.log 我的数组,但是当附加到 div 时,它的值显示为未定义

[英]I can console.log my array but it's values shows up as undefined when appended to a div

我可以在逐步遍历数组以构建列表项之前和之后对数组进行 console.log。 当我运行代码时,我在我的 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()

你有两个问题。

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

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

有关记录对象的延迟评估的更多信息,请参阅此问题

好的,这就引出了你的第二个问题。 您的日志语句在chrome.history.search回调之前执行。 这就是数组尚未填充的原因。 您需要使用承诺来确保您的代码按预期顺序执行。 为此,您应该使用像 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承诺”并祝你好运。 我希望这有助于让您朝着正确的方向开始。

如果您不想使用承诺:

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

异步代码很有趣。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM