javascript – 将C#3D阵列移植到JS 3D阵列

我开发了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);
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...