我有以下代码块
var cars = $('#mypage').data('carsdata');
if (cars == null) {
var clientId = $("input[name='ClientId']").val();
worksheet.ajax.execute('GET','/Cars/GetData/', { clientId: clientId }, function (res) {
if (res == "") {
return;
}
cars = res.Owners.filter(function (e) {
if (e.Email) {
return true;
}
return false;
}).map(function (e) {
return { key: e.Id, label: e.Email };
});
console.log("1" +cars.length); // cars lenght is 3
});
console.log("2" +cars.length); // cars is null
也许这是太多的代码,但问题是最后一行的 cars 变量始终为 null,即使我有 if 语句检查 null,在这种情况下我正在填充该变量,在
console.log("1" +cars.length);
汽车长度为 3,因此不为空。为什么这个 cars.length 没有复制到
console.log("2" +cars.length);
这一切都好吗map function
我是否正确填充了 cars 变量?
更新:
当汽车正确加载数据属性时,我将获取以下格式的数据
[Object { key=101, label="email@email.com"}, Object { key=22, label="email2@email.com"}, Object { key=442, label="email43@email.com"}]
最佳答案
那是因为您正在 worksheet.ajax.execute( )
的回调中填充 cars
它是异步调用的,因此您的应用程序通量与您的预期不同,请改为遵循以下顺序:
var cars = $('#mypage').data('carsdata');
//1) cars is null here
if (cars == null) {
//...
//2) get inside the if statement and start the ajax call
// cars is null here
worksheet.ajax.execute('GET','/Cars/GetData/', { clientId: clientId },
function (res) {
//...
//4) the ajax call return his value, and cars is updated
cars = res.Owners.filter( ... )
//5) now cars has the correct value
console.log("1" +cars.length); // cars lenght is 3
})
}
//3) get out of the if statement, print the console log
// cars is still null here
console.log("2" +cars.length); // cars is null
关于javascript - 映射函数且不填充变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39243620/