我开发了ac#library,它使用了3个项目,在那个特定的代码片段中继续,但是,我仍然需要在
javascript中使用该代码,所以我把它移植出来,事情是,我不认为我可以复制同样的逻辑,例如,我一直在考虑这几天,我无法得到答案.
在C#库中我有一个3D数组,它有点像应用程序中的核心属性,我似乎无法弄清楚如何在JS环境中使用它.
例如,我有这段代码:
- public Obj[,] objs = new Obj[18,14,8];
我会在每个单独的位置分配对象,并尝试将其移植到javascript,看起来会导致:
- var 3dArr = new Array();
- 3dArr[0] = new Array();
- 3dArr[0][0] = new Array();
这总是将数组对象保持在第一个位置,如果我设置其他任何我会丢失整个数组?或者我错了
解决方法
在撰写本文时,JavaScript中没有语言特性与C#中的多维数组非常相似.也不建议将普通数组暴露给整个应用程序的使用,因为这样可以通过向数组写入不应该保留的内容来轻易地错误地损害整个代码.
但是,将所需的数组封装到一个简单的新类中应该相对容易,例如:以下代码中的Array3d:
- /***** CODE OF THE ARRAY *****/
- function Array3d(width,height,depth,type) {
- this.width = width;
- this.height = height;
- this.depth = depth;
- this.type = type;
- this.array = new Array(width * height * depth);
- }
- Array3d.prototype = {
- get: function(x,y,z) {
- return this.array[calcIndex(this,x,z)];
- },set: function(x,z,item) {
- if (!(item instanceof this.type)) {
- throw new Error(item + ' is not instance of ' + this.type + '.');
- }
- this.array[calcIndex(this,z)] = item;
- }
- };
- function calcIndex(array3d,z) {
- return x + array3d.width * y + array3d.width * array3d.height * z;
- }
- /***** USAGE CODE *****/
- function Something(i) {
- this.index = i;
- }
- var array3d = new Array3d(10,11,12,Something);
- var something = new Something(11);
- array3d.set(4,something);
- var gettingBack = array3d.get(4,0);
- if (gettingBack === something) {
- console.log('1: Works as expected');
- }
- else {
- console.error('1: Not expected ' + gettingBack);
- }
- gettingBack = array3d.get(0,4);
- if (gettingBack == null) {
- console.log('2: Works as expected');
- }
- else {
- console.error('1: Not expected ' + gettingBack);
- }