推荐答案
// www.javascriptcn.com code example
function queryStringify(obj) {
return Object.keys(obj)
.map(key => {
const value = obj[key];
if (Array.isArray(value)) {
return value
.map((v, i) => `${encodeURIComponent(key)}[${i}]=${encodeURIComponent(v)}`)
.join('&');
} else if (typeof value === 'object' && value !== null) {
return Object.keys(value)
.map(subKey => `${encodeURIComponent(key)}[${subKey}]=${encodeURIComponent(value[subKey])}`)
.join('&');
} else {
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
}
})
.join('&');
}本题详细解读
1. 函数功能
queryStringify 函数的作用是将一个对象转换为查询字符串。查询字符串通常用于 URL 的查询参数部分,格式为 key1=value1&key2=value2。
2. 实现思路
- 遍历对象:使用
Object.keys(obj)获取对象的所有键,然后通过map方法遍历每个键值对。 - 处理数组:如果值是数组,则需要将数组的每个元素转换为
key[index]=value的形式,并使用&连接。 - 处理嵌套对象:如果值是对象且不为
null,则需要递归处理嵌套对象的键值对,并将其转换为key[subKey]=value的形式。 - 处理普通值:对于普通的值,直接将其转换为
key=value的形式。 - 编码处理:使用
encodeURIComponent对键和值进行编码,确保它们在 URL 中是合法的。
3. 示例
// www.javascriptcn.com code example
const obj = {
name: 'John',
age: 30,
hobbies: ['reading', 'swimming'],
address: {
city: 'New York',
zip: '10001'
}
};
console.log(queryStringify(obj));
// 输出: name=John&age=30&hobbies[0]=reading&hobbies[1]=swimming&address[city]=New%20York&address[zip]=100014. 注意事项
- 空值处理:如果对象中的某个值为
null或undefined,它们会被转换为字符串"null"或"undefined"。 - 嵌套对象:嵌套对象会被转换为
key[subKey]=value的形式,确保查询字符串的结构正确。 - 数组处理:数组会被转换为
key[index]=value的形式,确保数组元素的顺序和索引正确。