JavaScript : unable to merge two arrays

你说的曾经没有我的故事 提交于 2019-12-06 02:19:10

You're actually merging the arrays correctly and both methods would work (provided like others said that you use the return value of concat), but the result is empty because you're doing it when the answers from the ajax requests didn't arrive yet and the arrays are still empty.

When making ajax requests you must manipulate the result inside the success callback function, not at the same level of the ajax request code; for example

var myvec = [];
$.getjson(request_url, function(data) {
    myvec = data;
});
process(myvec);

will NOT work, because it's attempting to use the content of myvec right after the request has been submitted but before the reply arrived. Correct code is instead:

$.getjson(request_url, function(data) {
    // This code is executed when the data arrives from the server
    process(data);
});

If you need to concatenate the results of two async queries you must either chain them (make the second query only once the first returned) or you must wait for the second one to complete:

// First solution, simple but slower (waits for first reply
// before making second request)
$.getjson(request_url_1, function(data_1) {
    $.getjson(request_url_2, function(data_2) {
        process(data_1.concat(data_2));
    });
});

or

// Second solution; starts both requests and waits for both
// of them to complete before doing the processing

var count = 0;
var res = [];
function handle_data(data) {
    res = res.concat(data);
    count += 1;
    if (count == 2) {
        process(res);
    }
}

$.get(request_url_1, handle_data);
$.get(request_url_2, handle_data);

This crazy guess is simply coming from the frequency that this kind of error has in beginner code.

concat() will return a new array, not concat to the this. So:

var a=[1,2,3];
var b=[4,5,6];
var c=a.concat(b);
// a is still [1,2,3]
// c is [1,2,3,4,5,6]

Did you assign the result to another variable? For example:

var result = array1.concat(array2);

The .concat() method returns a new Array with the concatenated elements.

MDN Documentation on Array.prototype.concat

Use this

var newArray= array1.concat(array2);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!