Javascript splice方法从两个数组中删除值

时间:2012-12-17 10:23:50

标签: javascript splice

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

将对象复制到新对象..

试试这个..

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

这里只是复制对象的一个​​例子..检查出来

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