1

我想将 Json 保存到两个变量中,以便我可以操作一个,并在需要将数据恢复和重置为原始数据时保存原始变量。

Json 有 4 个项目。我有两个变量,它们最初都共享相同的数据,我可以看到它们在控制台中工作。但是,当我拼接“当前”变量时,“原始”变量也会以某种方式被拼接。我只想拼接、弹出和推送当前变量。

我的目标是拥有两个对象并且只操纵一个。我不能使用 cookie 或服务器。

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">

        var jsonOriginal;//used for the original json object
        var jsonCurrent;//used for the filtered json object that gets manipulated

        $.ajax({
          url: "sources/json.txt",
          dataType: 'json',
          success: (function(json) 
        { 
            //save the JSON into two variables for later use
             jsonOriginal = json;
             jsonCurrent= json;
             doSomething();
         })
        });


        function doSomething(){

            console.log(jsonOriginal);//has 4 items
            console.log(jsonCurrent);//has 4 items

            //Splice ONLY CURRENT
            jsonCurrent.items.splice(2, 3);//remove 2 items from jsonCurrent

            console.log(jsonOriginal);//has 2 items -- WHAT????
            console.log(jsonCurrent);//has 2 items as expected

            //reset Current to the Original
            jsonCurrent=jsonOriginal;//should go back to the 4 items

        }

</script>
4

1 回答 1

1

您需要制作 JSON 的副本,否则jsonOriginal只是jsonCurrent对同一对象的引用。采用

var jsonOriginal = jQuery.extend(true, {}, json);

代替

json原始 = json;

It would probably be a good idea to use the same method to copy jsonOriginal back when you want it back.

于 2012-01-18T01:17:27.430 回答