Mat*_* Ma 3 javascript multidimensional-array typedarray typed-arrays
我试图使用类型化数组而不是数组来减少内存:
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;
}Run Code Online (Sandbox Code Playgroud)
但是我无法创建多维Typed数组。为什么?我是否只需要将“数字”变量强制转换为Int8?
有类型的Int8Array只能包含8位整数。arr[i] = columns由于列的类型Int8Array无法转换为8位整数并(以任何有意义的方式)存储,因此将无法使用。
解决方案:要么创建arr一个通用Array元素,其元素可以是数组,要么(可能是更高级但通常性能更高的解决方案)将多维数组存储为单个平面数组,numrows * numcols并通过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);Run Code Online (Sandbox Code Playgroud)