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

前端之家收集整理的这篇文章主要介绍了javascript – 将C#3D阵列移植到JS 3D阵列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我开发了ac#library,它使用了3个项目,在那个特定的代码片段中继续,但是,我仍然需要在 javascript中使用该代码,所以我把它移植出来,事情是,我不认为我可以复制同样的逻辑,例如,我一直在考虑这几天,我无法得到答案.

在C#库中我有一个3D数组,它有点像应用程序中的核心属性,我似乎无法弄清楚如何在JS环境中使用它.

例如,我有这段代码

  1. public Obj[,] objs = new Obj[18,14,8];

我会在每个单独的位置分配对象,并尝试将其移植到javascript,看起来会导致:

  1. var 3dArr = new Array();
  2. 3dArr[0] = new Array();
  3. 3dArr[0][0] = new Array();

这总是将数组对象保持在第一个位置,如果我设置其他任何我会丢失整个数组?或者我错了

解决方法

在撰写本文时,JavaScript中没有语言特性与C#中的多维数组非常相似.也不建议将普通数组暴露给整个应用程序的使用,因为这样可以通过向数组写入不应该保留的内容来轻易地错误地损害整个代码.

但是,将所需的数组封装到一个简单的新类中应该相对容易,例如:以下代码中的Array3d:

  1. /***** CODE OF THE ARRAY *****/
  2. function Array3d(width,height,depth,type) {
  3. this.width = width;
  4. this.height = height;
  5. this.depth = depth;
  6. this.type = type;
  7. this.array = new Array(width * height * depth);
  8. }
  9.  
  10. Array3d.prototype = {
  11. get: function(x,y,z) {
  12. return this.array[calcIndex(this,x,z)];
  13. },set: function(x,z,item) {
  14. if (!(item instanceof this.type)) {
  15. throw new Error(item + ' is not instance of ' + this.type + '.');
  16. }
  17. this.array[calcIndex(this,z)] = item;
  18. }
  19. };
  20.  
  21. function calcIndex(array3d,z) {
  22. return x + array3d.width * y + array3d.width * array3d.height * z;
  23. }
  24.  
  25. /***** USAGE CODE *****/
  26. function Something(i) {
  27. this.index = i;
  28. }
  29.  
  30. var array3d = new Array3d(10,11,12,Something);
  31. var something = new Something(11);
  32. array3d.set(4,something);
  33. var gettingBack = array3d.get(4,0);
  34. if (gettingBack === something) {
  35. console.log('1: Works as expected');
  36. }
  37. else {
  38. console.error('1: Not expected ' + gettingBack);
  39. }
  40. gettingBack = array3d.get(0,4);
  41. if (gettingBack == null) {
  42. console.log('2: Works as expected');
  43. }
  44. else {
  45. console.error('1: Not expected ' + gettingBack);
  46. }

猜你在找的JavaScript相关文章