首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript剪接方法从两个数组中删除值

Javascript剪接方法从两个数组中删除值
EN

Stack Overflow用户
提问于 2012-12-17 10:23:50
回答 2查看 207关注 0票数 0

Javascript (使用jQuery):

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-17 10:28:56

javascript对象/数组通过引用存储。

如果你想要一份副本,那是个诡计:

代码语言:javascript
复制
if(typeof unused_paragraphs == "undefined") {
        var unused_paragraphs = [];
        for(var i = 0; i<paragraphs.length; i++) {
            unused_paragraphs[i] = paragraphs[i].slice(0);  
        }
}

代码语言:javascript
复制
unused_paragraphs[i] = paragraphs[i].slice(0);
票数 1
EN

Stack Overflow用户

发布于 2012-12-17 10:49:04

若要将该对象复制到新对象。

试试这个..。

代码语言:javascript
复制
var unused_paragraphs= jQuery.extend(true, {}, paragraphs);

这里只是复制对象的一个例子。看看这个

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13912270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档