In the project, we will encounter the need to convert objects into strings. Let me give a simple example below
const obj = {
a: "123",
b: "ppp",
c: "hah",
};
function objTostring(obj) {
const result = [];
for (var k in obj) {
console.log(obj, obj[k]);
result.push(`${k}=${obj[k]}`);
}
return result.join("&");
}
console.log(objTostring(obj));
就会得到结果 a=123&b=ppp&c=hah
之所以我们不用字符串 const result = '',而用数组类型 const result = [];就是为了简化,如果用了 字符串,那么最后还会有一个& 要去掉,那么我们的操作就又多了。