# 实现一个函数用来对 URL 的 querystring 进行编码
更多描述
示例,如
const data = {
a: 3,
b: 4,
c: 5
}
// 对 data 编码后得到 querystring 如下
const qs = 'a=3&b=4&c=5'
Issue
欢迎在 Issue 中交流与讨论: Issue 448 (opens new window)
Author
先上几个测试用例:
// a=3&b=4
stringify({ a: 3, b: 4 })
// a=3&b=
stringify({ a: 3, b: null })
// a=3&%E5%B1%B1=%E6%9C%88
stringify({ a: 3, '山': '月' })
只做一些基本的功能,满足以下条件
- 对 null/undefined/object 编码为空字符
- 对 key/value 记得 encodeURIComponent
- 不考虑数组及嵌套对象等复杂操作
function stringify (data) {
const pairs = Object.entries(data)
const qs = pairs.map(([k, v]) => {
let noValue = false
if (v === null || v === undefined || typeof v === 'object') {
noValue = true
}
return `${encodeURIComponent(k)}=${noValue ? '' : encodeURIComponent(v)}`
}).join('&')
return qs
}
这是一个最简单对 querystring 进行编码的函数,如果需要更复杂的需求如嵌套对象与数组可以参考 qs (opens new window)