0

如何使用 jquery 将此数组转换为用逗号分隔的字符串?

var array = $('#form').serializeArray();

谢谢!

4

2 回答 2

0

你可以这样做:

    var array = $('#form').serializeArray();
    var arrayString = '';

    jQuery.each(array, function () {
        if (arrayString == '' || arrayString == null) {
            arrayString = this + "";
        }
        else {
            arrayString = arrayString + "," + this;
        }
    });

或者

var array = $('#form').serializeArray();
arr = jQuery.map(array , function(n, i){
  return (n.toUpperCase() + i);
});
var arrayString = array.join(",");
于 2011-03-07T12:21:00.887 回答
0
$(function () {
  var ATTRIBUTE_SEPARATOR = ":";
  var PROPERTY_SEPARATOR = ", ";

  // EXAMPLE 1
  var serialize_array = $("#form").serializeArray();

  console.log(serialize_array);

  var converted_string_1 = $.map(serialize_array, function (prop, i) {
    return prop.name + ATTRIBUTE_SEPARATOR + prop.value;
  }).join(PROPERTY_SEPARATOR);

  console.log(converted_string_1);
  // a:a, b:b, c:c, d[]:d1, d[]:d2

  // EXAMPLE 2
  var serialized_string = $("#form").serialize();
  var converted_string_2 = decodeURIComponent(
    serialized_string
      .replace(/\&/g, PROPERTY_SEPARATOR)
      .replace(/\=/g, ATTRIBUTE_SEPARATOR)
  );

  console.log(converted_string_2);
  // a:a, b:b, c:c, d[]:d1, d[]:d2

  // EXAMPLE 3
  var converted_string_3 = JSON.stringify(serialize_array);

  console.log(converted_string_3);
  // [{"name":"a","value":"a"},{"name":"b","value":"b"},{"name":"c","value":"c"},{"name":"d[]","value":"d1"},{"name":"d[]","value":"d2"}]
});
于 2011-03-07T12:21:05.470 回答