简体   繁体   English

保留平面数组作为 2D 或 3D 数组的参考副本

[英]Keep a flat array as a reference copy to a 2D or 3D array

I have an array of point objects with x and y parameters such as:我有一个带有 x 和 y 参数的点对象数组,例如:

this.points = [p1, p2, p3,..];

Which I flatten as a 1D array like so:我将其展平为一维数组,如下所示:

this.coords = [];
for(let p of this.points){
 this.coords.push(p.x);
 this.coords.push(p.y);
}

The coords array is now:坐标数组现在是:

this.coords = [p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, ...]

My question is the following, I would like the modifications of either one of the arrays affect the other.我的问题如下,我想对 arrays 中的任何一个进行修改会影响另一个。 Because right now when I make a modification to either this.coords or this.points , the other one isn't updated.因为现在当我对this.coordsthis.points进行修改时,另一个没有更新。

Is there a way of doing this, or am I thinking about this wrong and there is a general guideline to coding coordinates that I do not know of yes?有没有办法做到这一点,或者我是否认为这是错误的,并且有一个我不知道的编码坐标的一般准则是的?

Thanks谢谢

JavaScript has two kinds of values: reference values and primitive values. JavaScript 有两种值:参考值和原始值。

Primitive values, like numbers, are copied and editing the copy never influences the original and the other way around.原始值(如数字)被复制,编辑副本永远不会影响原始值,反之亦然。 Because your x and y coordinates are probably primitive numerical values, this is not possible.因为您的 x 和 y 坐标可能是原始数值,所以这是不可能的。

You could encapsulate them in reference values, for example using arrays with 1 element.您可以将它们封装在参考值中,例如使用带有 1 个元素的 arrays。

 const points = [{x: [1], y: [2]}, {x: [3], y:[4]}]; const flat = [points[0].x,points[0].y,points[1].x,points[1].y]; flat[0][0]+=9; console.log(points[0].x)

But the question is why you want to do that in the first place.但问题是你为什么要首先这样做。 If that is some kind of extreme cache optimization, like making your own commercial game engine, any kind of method to synchronize the two data structures will probably more than neutralize that optimization benefit.如果这是某种极端的缓存优化,比如制作自己的商业游戏引擎,那么任何一种同步两种数据结构的方法都可能会抵消这种优化带来的好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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