Implode an array with JavaScript?

后端 未结 7 2115
醉话见心
醉话见心 2021-01-29 22:14

Can I implode an array in jQuery like in PHP?

7条回答
  •  广开言路
    2021-01-29 22:31

    array.join was not recognizing ";" how a separator, but replacing it with comma. Using jQuery, you can use $.each to implode an array (Note that output_saved_json is the array and tmp is the string that will store the imploded array):

    var tmp = "";
    $.each(output_saved_json, function(index,value) {
        tmp = tmp + output_saved_json[index] + ";";
    });
    
    output_saved_json = tmp.substring(0,tmp.length - 1); // remove last ";" added
    

    I have used substring to remove last ";" added at the final without necessity. But if you prefer, you can use instead substring something like:

    var tmp = "";
    $.each(output_saved_json, function(index,value) {
        tmp = tmp + output_saved_json[index];
    
        if((index + 1) != output_saved_json.length) {
             tmp = tmp + ";";
        }
    });
    
    output_saved_json = tmp;
    

    I think this last solution is more slower than the 1st one because it needs to check if index is different than the lenght of array every time while $.each do not end.

提交回复
热议问题