【问题标题】:Unable to get the required object returned from the callback function无法获取回调函数返回的所需对象
【发布时间】:2021-12-18 22:19:58
【问题描述】:

我试图从对象数组中返回所需的对象,其中数组索引作为参数传递给回调函数。例如。如果我想要数组索引 0 处的对象,我以这种方式调用 getInfo getInfo(0, data)。但是回调函数只返回索引而不是值。我尝试使用名为 myfunc 的简单函数进行测试,但这给了我想要的东西。这里有什么问题?

这是我的代码

const getInfo = (resource, callback) => {
let request = new XMLHttpRequest();

    request.addEventListener('readystatechange', () => {
        if(request.readyState === 4 && request.status === 200 )
            {
                const data = JSON.parse(request.responseText);
                console.log(data[resource]);
                myfunc(resource, data[resource]);
                callback(resource, data[resource]);
            }
    });

    request.open('GET','values.json');
    request.send();
};

const myfunc = (val,arr) =>{
    console.log(val,arr);
}

getInfo(0, data => {
    console.log(data);
    getInfo(2, data => {
        console.log(data);
        getInfo(1, data => {
                console.log(data);
        });
    });
});

values.json

[
    {"name" : "MM", "height" : "5 ft 2 inches"},
    {"name" : "DD", "height" : "5 ft 3 inches"},
    {"name" : "AA", "height" : "5 ft 5 inches"}
]

控制台输出

【问题讨论】:

    标签: javascript arrays json object callback


    【解决方案1】:

    你的回调只有一个参数,但你在调用回调时发送了两个参数

    getInfo(0, (index,data) => {
        console.log(data);
        getInfo(2, (index,data) => {
            console.log(data);
            getInfo(1, (index,data) => {
                    console.log(data);
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-17
      • 2014-05-15
      • 1970-01-01
      • 2013-02-28
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      相关资源
      最近更新 更多