0

「作成」ボタンをクリックすると、オブジェクトの最後の状態を配列に追加し、続行する準備ができた新しいクリーンを作成し、「続行」ボタンをクリックして実際のオブジェクトのみを変更すると、セクション配列内のすべてのオブジェクトが変更されるようになりますか?

説明資料:

HTML:

<button onclick="create()">Create</button>
<button onclick="add()">Continue</button>

JavaScript:

var sections = [];

create = function() {
    sections.push(section);

    section.array = [];
    section.c = 0;

    section.add();

    $("body").append("<br>Add to array at moment last state of object and make new one<br>" + JSON.stringify(sections) + "<br >");
}

add = function() {
    section.add();

    $("body").append("<br>continue only this object<br>" + JSON.stringify(sections) + "<br >");
}

var section = {
    array: [],
    c: 0,
    add: function() {
        section.c++;
        section.array.push(section.c);
    }
}​
4

2 に答える 2

1

(関数section内の) 1 つの変数のプロパティをリセットする代わりに、新しいセクション オブジェクトを作成する必要があります。create

var sections = [],
section = makeSection();

function create() {
    sections.push(section); // add the current section
    section = makeSection(); // make a new one
    section.add();

    $("body").append("<br>Add to array at moment last state of object and make new one<br>" + JSON.stringify(sections) + "<br >");
}

function add() {
    section.add();
    $("body").append("<br>continue only this object<br>" + JSON.stringify(sections) + "<br >");
}

function makeSection() {
    return {
        array: [],
        c: 0,
        add: function() {
            section.c++;
            section.array.push(section.c);
        }
    }​;
}

それでも、これはコンストラクター関数の場合だと思います。

function Section() {
    this.array = [];
    this.c = 0;
    // maybe do this automatically on constructing:
    // this.add();
    // sections.push(this);
}
Section.prototype.add = function() {
    this.c++;
    this.array.push(section.c);
}

new Section()の代わりに使用しmakeSection()ます。

于 2012-05-17T16:02:36.583 に答える
0

これを試して:

sections.push(JSON.parse(JSON.stringify(section)));

少しハックですがsections、参照ではなく、オブジェクトの新しいコピーを配列にプッシュし、オブジェクトの状態を効果的に保存します。このコードが実際に行っていることは、JSON ライブラリを使用してオブジェクトを ingstringifyしてからing することです。これにより、新しいオブジェクトが返されます。parse

于 2012-05-17T16:02:51.457 に答える