1

Json を 2 つの変数に保存して、1 つを操作できるようにし、元のデータを復元して元のデータにリセットする必要があるときに元の変数を保存したいと考えています。

Json には 4 つの項目があります。2 つの変数があり、どちらも最初は同じデータを共有しており、コンソールで動作していることがわかります。ただし、「現在の」変数をスプライスすると、「元の」変数も何らかの形でスプライスされます。現在の変数をスプライス、ポップ、プッシュしたいだけです。

私の目標は、2 つのオブジェクトを持ち、1 つだけを操作することです。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 のコピーを作成する必要があります。それ以外の場合は、同じオブジェクトへの単なる参照ですjsonOriginaljsonCurrent使用する

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

それ以外の

jsonOriginal = json;

jsonOriginal を戻したい場合は、同じ方法を使用して jsonOriginal をコピーすることをお勧めします。

于 2012-01-18T01:17:27.430 に答える