gpt4 book ai didi

javascript - ObjectToQuery 函数仅返回具有值的属性,但我想要所有属性

转载 作者:行者123 更新时间:2023-12-01 04:43:38 27 4
gpt4 key购买 nike

我使用此方法将对象转换为QueryString
ajax 发送请求需要 QueryString

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中省略了没有值的属性。
但我想要该对象的所有属性。对象属性是否有值(value)并不重要。

最佳答案

如果您传递值为 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);
}
}

关于javascript - ObjectToQuery 函数仅返回具有值的属性,但我想要所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33352697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com