JS Uint16Array 不会引发任何超出范围的异常

JS Uint16Array does not raise any out of range exception

这是一个愚蠢的问题,但我的代码中有一个错误,因为我在超出范围的索引处向 Uint16Array 添加值。但是JS引擎并没有报错,好像只是没有对附加值做任何处理。

例如:

>> var uint16 = new Uint16Array(2);
>> uint16[0] = 42;
>> uint16[1] = 32;
>> uint16[2] = 12;
>> uint16
Uint16Array(2) [42, 32]

标准的 JS 数组会附加新值并增加数组大小。

>> var arr = new Array(2);
>> arr[0] = 42;
>> arr[1] = 32;
>> arr[2] = 12;
>> arr
(3) [42, 32, 12]

有谁知道为什么我们在 Uint16Array 上有这种行为,为什么它不会引发任何类型的超出范围的异常?

因为是这样定义的。也许它会改变,但现在如果您尝试在超出范围的索引

处访问(读取或写入),它不会引发异常

However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound.

您将找到有关 TypedArray 的更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

还有好处:对于这种数组,您没有像 push, pop... 这样的常用方法。