簡體   English   中英

Javascript splice方法從兩個數組中刪除值

[英]Javascript splice method remove values from two arrays

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

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);

將obect復制到新對象..

嘗試這個..

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

這里只是復制對象的一個​​例子..檢查一下

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM