gpt4 book ai didi

javascript - javascript 中的意外标识符,但我已经声明了该变量

转载 作者:行者123 更新时间:2023-12-03 09:32:21 26 4
gpt4 key购买 nike

我已经查看这个文件一个小时并尝试了大量的排列。

$(document).ready(function() {

var unreadMessages = document.getElementsByClassName("unreadMessage");

var previousEntries;

chrome.storage.sync.get(null, {
var previousEntries;
previousEntries = (data["item"]);
});

console.log(previousEntries);


});


为什么 previousEntries 会抛出“未捕获的语法错误:意外的标识符”?

这似乎是最简单的任务。这是一个 } () 或 , 问题吗?

最佳答案

$(document).ready(function() {

var unreadMessages = document.getElementsByClassName("unreadMessage");

var previousEntries;

// vvvvvvvvvvvvvv
chrome.storage.sync.get(null, function(data){
// var previousEntries; And if you want to access this variable outside,
previousEntries = data["item"]; // don't redefine it here (no "var" keyword).
logValue(); // Now that the variable is set, you can use it
});

// console.log(previousEntries); // Undefined, because it is not set yet.

function logValue(){
console.log(previousEntries); // Now it should work (called from get's callback).
}

});

尚未设置变量的原因是 chrome.storage.sync.get 与 Ajax 或 setTimeout 一样,异步。想象一下这样做:

var myVar;

setTimeout(function(){
myVar = 'Hello world!';
console.log(myVar); // logs "Hello world!" to the console
}, 100);

alert(myVar); // alerts undefined

关于javascript - javascript 中的意外标识符,但我已经声明了该变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31464228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com