Search code examples
javascriptarrayssliceperlin-noise

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;
    }

Solution

  • 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);