多维数组深度拷贝函数
2.1.8 、deepCopy()方法
功能:多维数组深度拷贝函数,
场景:重玩本关是一个难点,难度在于三维数组的拷贝,只复制地址,不复制值,这意味着通关后的数组再也回不到初始化时的数组,也就实现不了重玩本关的功能。javascrit数组数据类型提供了slice(0)和concat()函数实现数组的深拷贝,但只局限于一维数组,在二维,三维,四维中不起作用。
为了解决此问题,特提供深度拷贝函数解决此问题。
参数:无参数
返回值: 数组
示例: var A=[
[
[1,2,1,1,1,1,1,1,1,1],
[1,0,0,0,0,1,0,0,0,1],
[1,0,3,0,0,0,0,0,0,1],
[1,0,0,0,0,1,0,0,0,1],
[1,0,1,1,0,1,0,0,1,1],
[1,0,0,1,0,0,0,3,0,1],
[1,0,0,1,0,1,0,0,0,1],
[1,0,0,3,0,0,0,0,0,1],
[1,0,0,0,1,1,0,0,0,1],
[1,1,1,1,1,1,1,1,4,1]
],
[
[1,0,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,3,0,0,0,1],
[1,1,1,0,0,0,0,0,0,1],
[1,0,0,1,0,0,3,0,1,1],
[1,0,0,1,0,1,0,0,1,1],
[1,0,0,1,1,1,0,0,0,1],
[1,0,0,0,0,0,3,0,0,1],
[1,0,0,3,0,0,0,0,0,1],
[1,1,1,1,1,1,1,4,1,1]
],
]
var B=A.deepCopy();
结果:全新的一个三维数组,当修改数组A的值时,B的值不会发生变化,适合于游戏多关卡场景。
[
[
[1,2,1,1,1,1,1,1,1,1],
[1,0,0,0,0,1,0,0,0,1],
[1,0,3,0,0,0,0,0,0,1],
[1,0,0,0,0,1,0,0,0,1],
[1,0,1,1,0,1,0,0,1,1],
[1,0,0,1,0,0,0,3,0,1],
[1,0,0,1,0,1,0,0,0,1],
[1,0,0,3,0,0,0,0,0,1],
[1,0,0,0,1,1,0,0,0,1],
[1,1,1,1,1,1,1,1,4,1]
],
[
[1,0,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,3,0,0,0,1],
[1,1,1,0,0,0,0,0,0,1],
[1,0,0,1,0,0,3,0,1,1],
[1,0,0,1,0,1,0,0,1,1],
[1,0,0,1,1,1,0,0,0,1],
[1,0,0,0,0,0,3,0,0,1],
[1,0,0,3,0,0,0,0,0,1],
[1,1,1,1,1,1,1,4,1,1]
],
]
尝试一下:
var A=[1,2,1,1,1,1,1,1,1,1]; var B=A.deepCopy(); A[1]=3; B
返回结果