简体   繁体   中英

Array won't split (using splice(0))

I am attempting something like a perlin noise map, but my array won't duplicate! As a result the array value exceeds the expected value (>2).

Array " map " consist of only 1's and 0's.

A copy of map is made (called cache ) and values from the array " cache " are added to the array " map ".

Some values of cache are added to map multiple times.

The problem is any change made to " map " appears to be duplicated on " cache ", very frustrating. I'm not familiar enough with javascript to know what I did wrong.

relivant code:

    var map = terrainSeed(); //returns an array of 1's & 0's (random)
    map = terrainGen(map, map, 2, 2);   

    function terrainGen(mapNew, mapOld, x, y)          
    {            
        var cache = mapOld.slice(0);
        var asdf = 0;

        //if(x >=2) if(y >=2)
        for(var i = 0; i < cache.length; i++)
        {
            for(var j = 0; j < cache[i].length; j++)
            {
                var save = mapNew[i][j];
                asdf = cache[(Math.floor(i/x))][(Math.floor(j/y))];
                mapNew[i][j] += asdf;    

                if(mapNew[i][j]>2) alert(save + " + " + asdf + " = " + mapNew[i][j] + " (" + i + ", " + j + ")");                        
            }
         }
        return mapNew;
    }

as slice is doing shallow copy, what you need is a deep copy. so either use some third-party lib like JQuery, Lo-Dash or implement it by your self.

Using JQuery

var cache = $.extend(true, [], mapOld);

Using Lo-Dash

var cache = _.cloneDeep(mapOld);

As an alternative to elaijuh 's answer, using pure JavaScript, you'd need to loop through the mapOld array values to create a new array... Here is how it would:

var cache = new Array;
for (var i=0;i<mapOld.length;i++) {
  cache[i] = mapOld[i];
}

You're simply pulling the values from mapOld and putting them into cache ... This is probably how libraries implement it, accept in a function... Here is how you'd make a function:

clone = function(input){
  if (input instanceof Array) {
    var output = new Array;
    for (var i=0;i<input.length;i++) {
      output[i] = input[i];
    }
    return output;
  }
}

// Then using...
cache = clone(mapOld);

Here is an example JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM