[英]why is javascript not modifying my variable?
我使用以下javascript函數遇到的問題是,它以“不是程序員”的身份返回最流行的字符串值,因此盡管它在執行我的console.log命令的位置時執行了正確的操作,但返回的最流行的變量hasn沒有被修改。 如果我在頂部修改變量,為什么它不返回修改...就像javascript生成一個實例一樣,它僅在測試函數的本地設置中起作用(如果我將console.log語句打印出來,正確的數據)。 為什么是這樣 ?
var mostPopular = "not a programmer";
var totalResults = 0;
function myfunction() {
var listOfLanguages = ["Java", "C", "C++", "PHP", "C#", "Visual Basic", "Python", "Objective-C", "Perl", "Javascript", "Ruby"];
for (var i = 0; i < listOfLanguages.length - 1; i++) {
chrome.history.search({
text: listOfLanguages[i],
maxResults: 100
}, function (search_results) {
var countOfResults = search_results.length;
var langOfResults = listOfLanguages[i - 1];
test(countOfResults, langOfResults);
});
}
console.log(mostPopular);
}
function test(count, lang) {
if (count > totalResults) {
totalResults = count;
mostPopular = lang;
}
}
window.onload = myfunction;
如上所述,歷史記錄搜索是異步的,因此完成后需要回調執行
它將像下面這樣工作:
var mostPopular = "not a programmer";
var totalResults = 0;
function myfunction() {
var listOfLanguages = ["Java", "C", "C++", "PHP", "C#", "Visual Basic", "Python", "Objective-C", "Perl", "Javascript", "Ruby"];
for (var i = 0; i < listOfLanguages.length - 1; i++) {
chrome.history.search({
text: listOfLanguages[i],
maxResults: 100
}, function (search_results) {
var countOfResults = search_results.length;
var langOfResults = listOfLanguages[i - 1];
test(countOfResults, langOfResults);
console.log(mostPopular);
// The Code will execute whenever the history search results are returned
});
}
// Any code here will be exceuted irrespective of the history search completed or not
}
function test(count, lang) {
if (count > totalResults) {
totalResults = count;
mostPopular = lang;
}
}
window.onload = myfunction;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.