0

Javascript (using 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);

    });

});

My question is why when I use splice method on unused_paragraphs variable it also remove the value from the paragraphs variable

Later edit JSFiddle

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50

2 Answers2

1

javascript objects/array are stored by reference.

If you want a copy that's a trick:

if(typeof unused_paragraphs == "undefined") {
        var unused_paragraphs = [];
        for(var i = 0; i<paragraphs.length; i++) {
            unused_paragraphs[i] = paragraphs[i].slice(0);  
        }
}

and

unused_paragraphs[i] = paragraphs[i].slice(0);
Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
  • I've tried this but now the problem is that `splice` method is not working anymore.. The found value is not removed from the array.. Why's that? – Mihai Matei Dec 17 '12 at 10:32
  • This solution works for me @MateiMihai, did you change both lines? which version of jQuery are you using? – I.G. Pascual Dec 17 '12 at 10:46
  • For an advanced copy function, you can see also this answer (http://stackoverflow.com/questions/2294703/multidimensional-array-cloning-using-javascript). – Luca Rainone Dec 17 '12 at 11:07
  • Thank you for your answer, it was what I've expected but I have to review my code because now there is something else which is not working. Thank you – Mihai Matei Dec 17 '12 at 11:30
1

to copy the obect to new object..

try this..

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

here is just an example of copied objects.. check it out

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

bipen
  • 36,319
  • 9
  • 49
  • 62