SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast sffc's Avatar
    Join Date
    Jul 2006
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Assign "this" to a New Variable

    I'm playing around with the Array prototype. Right now, I'm working on a "shuffle" method:
    Code JavaScript:
    Array.prototype.shuffle = function(){
    	var returnarr = new Array();
    	var temparr = this;
    	while(temparr.length){
    		var shufflerand = Math.floor(Math.random()*temparr.length);
    		returnarr.push(temparr[shufflerand]);
    		temparr.splice(shufflerand, 1);
    	}
    	return returnarr;
    }
     
    var arrA = new Array("Apples", "Bananas", "Cherries");
    var arrB = arrA.shuffle();
    alert(arrB); // for example: Bananas,Apples,Cherries
    alert(arrA); // empty
    The method returns a shuffled array, just as I'd expect. What I didn't expect, though, is that it simultaneously empties the original array, arrA.

    I ran this code through Firebug, and whenever the "temparr.splice" line runs, a value is removed from this, not just temparr. The reason I assigned this to the variable temparr was so that I could splice values from the middle of temparr without affecting this. However, it seems that temparr is acting as a reference to this rather than a copy.

    How can I make this copy itself into the variable temparr so that we can safely splice values from temparr without affecting the original array?
    "I haven't failed, I just found
    100,000 ways that don't work"
    Thomas Edison

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,716
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    A common technique is to use the slice method to slice nothing off, effectively cloning the array.

    slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array
    Code javascript:
    var temparr = this.slice(0);
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Enthusiast sffc's Avatar
    Join Date
    Jul 2006
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That does it! I had forgotten that objects got passed as references rather than values when assigned to variables. Thanks!
    "I haven't failed, I just found
    100,000 ways that don't work"
    Thomas Edison


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •