簡體   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