Javascript 通过回调为变量赋值

Javascript 通过回调为变量赋值,javascript,google-chrome-extension,callback,Javascript,Google Chrome Extension,Callback,所以我的chrome扩展出现了这个问题: function comparingDates(fn) { var currentDate = new Date(); var j; chrome.storage.sync.get("storeDates", function comparing(items) { if (!chrome.runtime.error) { var arrayDates = items.storeDates; var i = 0;

所以我的chrome扩展出现了这个问题:

function comparingDates(fn) {
var currentDate = new Date();
var j;
chrome.storage.sync.get("storeDates", function comparing(items) {
    if (!chrome.runtime.error) {
        var arrayDates = items.storeDates;
        var i = 0;
        do {
            if (arrayDates[i].date == currentDate.getDate()) {
                j = i; // problemas al enviar el j
            };
            i++
        } while (!j);
        fn(j);
        };
    });
};
var currentDay;
 comparingDates(function (l1) {
    if (!l1) {
        console.log("error");
    } else {
        currentDay = l1;
        console.log("succes");
};
storeDates对象包含多个日期,这些日期与currentDate进行比较。当do/while循环找到匹配项时,它假定为j赋值。但由于某些原因,在发送回调时,不会对currentDay进行分配

我试图掌握回调理论并将其实现到我的代码中,但大多数我能找到的示例只是打印结果,而不是指定给某个值。
关于如何解决此问题的任何建议

查看评论后,我找到了问题的解决方案:

function comparingDates(fn) {
var currentDate = new Date();
var j;
chrome.storage.sync.get("storeDates", function comparing(items) {
if (!chrome.runtime.error) {
    var arrayDates = items.storeDates;
    var j = arrayDates.findIndex(x => x.date == currentDate.getDate());
    console.log(j);
    fn(j);
        };
    });
};

var currentDay;
comparingDates(function (l1) {
if (!l1) {
    console.log("error");
} else {
    currentDay = l1;
    console.log("succes");
};  

您有一些语法错误,修复它们可能有助于解决您的问题。@evolutionxbox您能指出您指的是哪些错误吗?提前,你有不匹配的括号并且你没有关闭比较日期,当你用数组索引调用“fn”时,arrayDates将不可用,也许这无关紧要。如果currentDate与arrayDates中的任何内容都不匹配,则在尝试使用i==arrayDates.length读取
arrayDates[i]
的日期属性时将产生错误。我建议您使用array.find或array.findIndex而不是I,j循环结构。由于chrome.*API回调是异步的,因此
currentDay
变量将仅在回调中定义。或者在后续JS引擎循环事件中运行并与变量驻留在同一闭包中的代码中。看见