javascript - 映射函数且不填充变量

标签 javascript jquery

我有以下代码块

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/

相关文章:

javascript 数据不会显示在 php codeigniter 中

jquery - 使用 Kwicks 打开 Accordion slider 的第一行时遇到问题

javascript - 使用图像数组列表的 simplegallary.js 显示适合桌面屏幕的图像

javascript - 在不删除 0 "zero(s)"的情况下将十进制转换为字符串?

javascript - 如何节省 onscroll 函数的 JS DOM 调用

javascript - 在 HTML/HTML5 中使用 JS 的不规则 anchor 和形状

javascript - 如何向我的网站添加缩略图,以便当有人在 Twitter 或 Facebook 上分享链接时它会显示图像和链接?

javascript - .map() 是否足够,或者我应该在 React Native 中使用 ListView(或 FlatList)?

javascript - Chrome 扩展程序使用 JavaScript 隐藏 webkitNotifications.createHTMLNotification 通知气球

JQUERY 输入字段值存储在变量中