javascript编码uri和数组/对象

javascript编码uri和数组/对象,javascript,arrays,foreach,javascript-objects,encodeuricomponent,Javascript,Arrays,Foreach,Javascript Objects,Encodeuricomponent,我正在尝试编写一个函数,该函数将在数组或对象上运行encodeURIComponent,而不管深度如何。在我返回最终结果之前,一切似乎都进展顺利 <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script> <s

我正在尝试编写一个函数,该函数将在数组或对象上运行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>

函数encodeURI_数组($array){
$Result=[];
如果($Array!==null&&typeof$Array==='object'){
//for(变量键在$Array中){
key($Array).forEach(函数(键){
如果($Array[key]!==null&&typeof$Array[key]===='object'){
log(“编码数组:“+key+”:“+$array[key]);
$Result[key]=encodeURI_数组($array[key]);
}否则{
$Result[key]=encodeURIComponent($Array[key],“UTF-8”)。替换(/\+/g.)。替换(“%26”,“&”)。替换(“%2C”,“,”);
log(“编码字符串:“+key+”:“+$Result[key]);
}
});
控制台日志(“最终结果”);
console.log($Result);
返回$Result;
}否则{
$Result=encodeURIComponent($Array,“UTF-8”)。替换(/\+/g.)。替换(“%26”、“&”)。替换(“%2C”、“,”);
log(“编码字符串:+$Result”);
返回$Result;
}
}
$TestArray=[{“Key1”:“Value1”}、{“Key2”:“Value2”}、{“Key3”:“Value3”}];
$TestArray2={“键”:“值”};
(encodeURI_数组($TestArray));
//log(encodeURI_数组($TestArray2));

对于这个脚本,最后一个结果只返回数组中的最后一个对象,而它应该返回一个对象数组。

你不能只使用JSON吗?JavaScript不是PHP。你不需要变量名上的前缀
$
,但你需要使用
var
将它们声明为局部变量。尤其是
$result
。你没有对返回值做任何事情,这是没有帮助的。你不应该在循环中需要该条件-只需进行递归调用。你的函数会自行判断它是否在对象/数组上被调用。避免代码重复。你的
替换
规则很奇怪。它们有什么用?