【问题标题】:Jquery Save Json to Two Variables and Then Splice Only OnejQuery 将 Json 保存到两个变量,然后只拼接一个
【发布时间】:2012-02-12 19:18:33
【问题描述】:

我想将 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>

【问题讨论】:

  • 请显示返回的json对象/

标签: jquery ajax json variables splice


【解决方案1】:

您需要复制 JSON,否则 jsonOriginaljsonCurrent 只是对同一对象的引用。使用

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

而不是

json原始 = json;

当你想要它时,使用相同的方法将 jsonOriginal 复制回来可能是个好主意。

【讨论】:

  • 好的,我想我明白你的意思了。当我重置时,我应该使用 jsonCurrent =jQuery.extend(true, {}, jsonOriginal);对吗?
  • 没错。本质上,您希望 jsonOriginal 保持不变,因此您始终需要复制它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
相关资源
最近更新 更多