0

Javascript(jQueryを使用):

var paragraphs = [
    ['This is my first paragraph content of the first array', 'This is my second paragraph content of the first array', 'This is my third paragraph content of the first array'],
    ['This is my first paragraph content of the second array', 'This is my second paragraph content of the second array', 'This is my third paragraph content of the second array']
],
text_box_value,
unused_paragraphs = null;

$(document).ready(function(){
    $('input#text_box').keyup(function(){
        text_box_value = $(this).val(); 
    });

    $('input#submit_button').click(function(){
        if(unused_paragraphs === null) {
            unused_paragraphs = paragraphs; 
        }

        for(var i = 0; i < unused_paragraphs.length; i++) {
            if(unused_paragraphs[i].length == 0)
                unused_paragraphs[i] = paragraphs[i];

            while(unused_paragraphs[i].length != 0) {
                var rand = Math.floor(Math.random() * unused_paragraphs[i].length);
                if(unused_paragraphs[i][rand].search(text_box_value) !== -1) {
                    $("#paragraphs_container").append('<p>' + unused_paragraphs[i][rand] + '</p>');
                    break;
                }

                unused_paragraphs[i].splice(rand, 1);
            }   
        }

        console.log(unused_paragraphs);
        console.log(paragraphs);

    });

});

私の質問は、変数でspliceメソッドを使用すると、変数unused_paragraphsから値も削除される理由ですparagraphs

後で JSFiddleを編集する

4

2 に答える 2

1

javascriptオブジェクト/配列は参照により保存されます。

トリックのコピーが必要な場合:

if(typeof unused_paragraphs == "undefined") {
        var unused_paragraphs = [];
        for(var i = 0; i<paragraphs.length; i++) {
            unused_paragraphs[i] = paragraphs[i].slice(0);  
        }
}

unused_paragraphs[i] = paragraphs[i].slice(0);
于 2012-12-17T10:28:56.620 に答える
1

オブジェクトを新しいオブジェクトにコピーします。

これを試して..

var unused_paragraphs= jQuery.extend(true, {}, paragraphs);

これはコピーされたオブジェクトの単なる例です。チェックしてください

http://jsfiddle.net/5ExKF/3/

于 2012-12-17T10:49:04.987 に答える