无法获取从回调函数返回的所需对象

Unable to get the required object returned from the callback function

提问人:mzaidi 提问时间:11/5/2021 更新时间:11/5/2021 访问量:33

问:

我正在尝试从 objects 数组返回所需的对象,其中数组索引作为参数传递给回调函数。例如,如果我希望数组索引为 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"}
]

控制台输出

enter image description here

JavaScript 数组 JSON 对象 回调

评论


答:

2赞 adhi narayan 11/5/2021 #1

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

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