我试图编写一个函数,无论深度如何,都会在数组或对象上运行encodeURIComponent。在我返回最终结果之前,这一切似乎都很顺利。
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script>
function encodeURI_array($Array) {
$Result = [];
if($Array !== null && typeof $Array === 'object') {
//for(var key in $Array) {
Object.keys($Array).forEach(function (key) {
if($Array[key] !== null && typeof $Array[key] === 'object') {
console.log("encode array: " + key + " : " + $Array[key]);
$Result[key] = encodeURI_array($Array[key]);
} else {
$Result[key] = encodeURIComponent($Array[key],"UTF-8").replace(/\+/g, ' ').replace("%26","&").replace("%2C",",");
console.log("encode strings: " + key + " : " + $Result[key]);
}
});
console.log("Final result");
console.log($Result);
return $Result;
} else {
$Result = encodeURIComponent($Array,"UTF-8").replace(/\+/g, ' ').replace("%26","&").replace("%2C",",");
console.log("encode string: " + $Result);
return $Result;
}
}
$TestArray = [{"Key1":"Value1"},{"Key2":"Value2"},{"Key3":"Value3"}];
$TestArray2 = {"Key":"Value"};
(encodeURI_array($TestArray));
//console.log(encodeURI_array($TestArray2));
</script>
对于这个脚本,最后一个结果只返回数组中应该返回一个对象数组的最后一个对象。