JavaScript多维类型化数组(Int8Array)示例

6

I tried to use Typed arrays instead of arrays, to reduce memory:

function createarrayInt8(numrows,numcols,number){
       
 var arr = new Int8Array(numrows);
         
 for (var i = 0; i < numrows; ++i){
  var columns = new Int8Array(numcols);
  for (var j = 0; j < numcols; ++j){
   columns[j] = number;
  }
  arr[i] = columns;
 }
  
 return arr; 
}

但我无法创建多维类型数组。 为什么? 我只需要将“number”变量转换为Int8吗?


1
一个类型化数组只能存储相同类型的值。因此,uint8 数组只能存储无符号 8 位整数,而不能存储 uints 的数组。 - le_m
我差点也这么想 :). 但是如何使它的多维数组仅存储无符号8位整数以减少内存使用呢? - Matthias Ma
1个回答

9

一个类型为Int8Array的数组只能包含8位整数。所以arr[i] = columns是无法起作用的,因为columns是Int8Array类型,不能被转换并存储(以任何有意义的方式)为8位整数。

Solution: Either make arr a generic Array whose elements can be arrays or - probably the more advanced but usually more performant solution - store your multidimensional array as a single flat array of size numrows * numcols and access an element via arr[column + row * numcols]:

var numrows = 5, numcols = 4;
var arr = new Int8Array(numrows * numcols).fill(0);

arr[3 + 1 * numrows] = 1; // col = 3, row = 1

console.log (arr);


我可以将这个读取操作中的numcols与行数相乘(即arr[column + row * numcols]),而将写入操作中的numrows与行数相乘(即arr[column + row * numrows])吗?这似乎不对,因为读/写公式是不一致的。 - DrSensor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接