Implode an array with JavaScript?

后端 未结 7 2098
醉话见心
醉话见心 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.

    0 讨论(0)
  • 2021-01-29 22:35

    You can do this in plain JavaScript, use Array.prototype.join:

    arrayName.join(delimiter);
    
    0 讨论(0)
  • 2021-01-29 22:39

    Like This:

    [1,2,3,4].join('; ')
    
    0 讨论(0)
  • 2021-01-29 22:39

    For future reference, if you want to mimic the behaviour of PHP's implode() when no delimiter is specified (literally just join the pieces together), you need to pass an empty string into Javascript's join() otherwise it defaults to using commas as delimiters:

    var bits = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'];
    alert(bits.join());    // H,e,l,l,o, ,W,o,r,l,d
    alert(bits.join(''));  // Hello World
    
    0 讨论(0)
  • 2021-01-29 22:48

    Use join() method creates and returns a new string by concatenating all of the elements in an array.

    Working example

    var arr= ['A','b','C','d',1,'2',3,'4'];
    var res= arr.join('; ')
    console.log(res);

    0 讨论(0)
  • 2021-01-29 22:52

    Array.join is what you need, but if you like, the friendly people at phpjs.org have created implode for you.

    Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.

    0 讨论(0)
提交回复
热议问题