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

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

    });

});

我的问题是为什么当我在 unused_pa​​ragraphs 变量上使用 splice 方法时,它也会从 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);

关于Javascript splice 方法从两个数组中删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13912270/

相关文章:

javascript - AJAX 和 IE - 无法获取属性错误

JavaScript 确认在某些操作系统上陷入无限循环的模糊/焦点事件

javascript - 显示到页面后如何编辑和删除json

javascript - 无法使用 for 循环从多维数组中删除元素 (javascript)

javascript 使用私有(private)数组创建对象

javascript - 如何仅在 props 更新后运行 onSubmit={}?

Javascript动态下拉菜单我也可以在按钮中看到它

javascript - 在 React 中解构状态/ Prop

javascript - 在多维数组上使用 javascript forEach 和拼接

jquery - 拼接 jQuery 元素数组