ObjectToQuery函数返回只是属性值,但我想要所有的属性

ObjectToQuery function return just the properties have values but i want all the properties

本文关键字:属性 我想要 函数 返回 ObjectToQuery      更新时间:2023-09-26

我使用此方法是为了将对象转换为QueryString
QueryStringajax发送请求所必需的。

var objectToQueryString = function(a) {
  var prefix, s, add, name, r20, output;
  s = [];
  r20 = /%20/g;
  add = function(key, value) {
    // If value is a function, invoke it and return its value
    value = (typeof value == 'function') ? value() : (value == null ? "" : value);
    s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
  };
  if (a instanceof Array) {
    for (name in a) {
      add(name, a[name]);
    }
  } else {
    for (prefix in a) {
      buildParams(prefix, a[prefix], add);
    }
  }
  output = s.join("&").replace(r20, "+");
  return output;
};
function buildParams(prefix, obj, add) {
  var name, i, l, rbracket;
  rbracket = /'[']$/;
  if (obj instanceof Array) {
    for (i = 0, l = obj.length; i < l; i++) {
      if (rbracket.test(prefix)) {
        add(prefix, obj[i]);
      } else {
        buildParams(prefix + "%" + (typeof obj[i] === "object" ? i : "") + "%", obj[i], add);
      }
    }
  } else if (typeof obj == "object") {
    // Serialize object item.
    for (name in obj) {
      buildParams(prefix + "%" + name + "%", obj[name], add);
    }
  } else {
    // Serialize scalar item.
    add(prefix, obj);
  }
}

下面的代码成功地将对象转换为QueryString,但是没有值的属性在返回QueryString中被省略。
但是我想要对象的所有属性。对象属性是否有值并不重要

如果您传递的属性值为null,则此调用中的'obj'参数将为null:

function buildParams(prefix, obj, add) {

你可以测试你的结果,当你改变你的'buildParams'函数:

function buildParams(prefix, obj, add) {
    obj = obj || "";
    var name, i, l, rbracket;
    rbracket = /'[']$/;
    if (obj instanceof Array) {
        for (i = 0, l = obj.length; i < l; i++) {
            if (rbracket.test(prefix)) {
                add(prefix, obj[i]);
            } else {
                buildParams(prefix + "%" + (typeof obj[i] === "object" ? i : "") + "%", obj[i], add);
            }
        }
    } else if (typeof obj == "object") {
        // Serialize object item.
        for (name in obj) {
            buildParams(prefix + "%" + name + "%", obj[name], add);
        }
    } else {
        // Serialize scalar item.
        add(prefix, obj);
    }
}