Javascript array: an independent copy

  • user warning: Table 'allaboutwebstuff.comments' doesn't exist query: SELECT COUNT(*) FROM comments c WHERE c.nid = 51 AND c.status = 0 in /home/albertoperego/allaboutwebstuff.com/modules/comment/comment.module on line 992.
  • user warning: Table 'allaboutwebstuff.comments' doesn't exist query: SELECT c.cid as cid, c.pid, c.nid, c.subject, c.comment, c.format, c.timestamp, c.name, c.mail, c.homepage, u.uid, u.name AS registered_name, u.signature, u.picture, u.data, c.thread, c.status FROM comments c INNER JOIN users u ON c.uid = u.uid WHERE c.nid = 51 AND c.status = 0 ORDER BY c.thread DESC LIMIT 0, 50 in /home/albertoperego/allaboutwebstuff.com/modules/comment/comment.module on line 992.

Very very often I do the following error when I need to work on a copy of an array and then the whole code doesn't work and it's always hard to realize what's wrong because it look right but it's not!
Let's have a look at the following code:

var music_genre = ['classic', 'dance', 'metal'];

//copy of the array
var favourite_genre = music_genre;

//extract the last element of the array
favourite_genre.pop();

alert(favourite_genre);  //['classic', 'dance']
alert(music_genre);      //['classic', 'dance'] TOO!!

That's because you need to use the method slice() of the class Array, which returns an independent copy of the array and any modify on it wont affect the original one.
Do something like this:

var favourite_genre = music_genre.slice(0);

favourite_genre.pop();

alert(favourite_genre);  //['classic', 'dance']
alert(music_genre);      //['classic', 'dance', 'metal']

Tags:
Share and Enjoy: