【问题标题】:Javascript splice method remove values from two arraysJavascript拼接方法从两个数组中删除值
【发布时间】:2012-12-17 10:23:50
【问题描述】:

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_paragraphs 变量上使用 splice 方法时,它也会从 paragraphs 变量中删除值

稍后编辑 JSFiddle

【问题讨论】:

  • 听起来你只有一个数组,但有两个变量引用它。

标签: javascript splice


【解决方案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);

【讨论】:

  • 我已经尝试过了,但现在的问题是 splice 方法不再起作用了。找到的值没有从数组中删除。这是为什么呢?
  • 这个解决方案对我有用@MateiMihai,你改变了两条线吗?你用的是哪个版本的jQuery?
  • 对于高级复制功能,您也可以看到这个答案(stackoverflow.com/questions/2294703/…)。
  • 感谢您的回答,这是我的预期,但我必须检查我的代码,因为现在还有其他东西不起作用。谢谢
【解决方案2】:

将对象复制到新对象..

试试这个..

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

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

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

【讨论】:

    猜你喜欢
    • 2012-07-16
    • 2014-01-22
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 2019-10-05
    • 2019-11-08
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多