[英]Array won't split (using splice(0))
I am attempting something like a perlin noise map, but my array won't duplicate! 我正在尝试类似perlin噪声贴图的方法,但是我的阵列不会重复! As a result the array value exceeds the expected value (>2).
结果,数组值超过了预期值(> 2)。
Array " map " consist of only 1's and 0's. 数组“ map ”仅包含1和0。
A copy of map is made (called cache ) and values from the array " cache " are added to the array " map ". 制作一个map副本(称为cache ),并将数组“ cache ”中的值添加到数组“ 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. 问题是对“ map ”所做的任何更改似乎都在“ cache ”上重复了,非常令人沮丧。 I'm not familiar enough with javascript to know what I did wrong.
我对javascript不够熟悉,无法知道我做错了什么。
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. 由于
slice
正在执行浅表复制,因此您需要的是深表复制。 so either use some third-party lib like JQuery, Lo-Dash or implement it by your self. 因此,要么使用诸如JQuery,Lo-Dash之类的第三方库,要么自行实现它。
Using JQuery 使用JQuery
var cache = $.extend(true, [], mapOld);
Using Lo-Dash 使用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: 作为使用纯JavaScript的elaijuh答案的替代方法,您需要遍历mapOld数组值以创建一个新数组...这是这样的:
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: 您只需从
mapOld
提取值并将其放入cache
……这可能是库如何实现它,在函数中接受...这是您将如何创建函数:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.