简体   繁体   English

有没有一种方法可以将类型化数组设置为零?

[英]Is there a method to set a typed array to zero?

Is there a way to set every element of a Javascript typed array (ie a Uint32Array ) to some value (something like the C function memset would do)?有没有办法将 Javascript类型数组(即Uint32Array )的每个元素设置为某个值(类似于 C function之类的)?

var foo = new Uint32Array(16384);
for (int i=0; i<foo.length; i++) {   // I want to do this without a for-loop
    foo[i] = 0xdeadbeef;
}

Generally, the answer in this case is going to be no.一般来说,这种情况下的答案是否定的。 In JavaScript you either declare things fully when you create them via literal syntax:在 JavaScript 中,您可以在通过文字语法创建它们时完全声明它们:

var Arr1 = [1,2,3,4,5];

Or you assign values to them (via loops when necessary for sequences):或者您为它们分配值(在序列需要时通过循环):

var Arr2 = Array(32);

for (var i = 0, j < Arr2.length; i < j; ++i) { Arr2[i] = 0xdeadbeef; }

JavaScript is a language that benefits from only accessing Arr2.length once when possible, so this syntax should net a performance benefit over other variations, but there's not a way to assign all positions in an array to a specific value other than undefined, which is what you get when you initialize with a size. JavaScript 是一种语言,它受益于尽可能仅访问 Arr2.length 一次,因此这种语法应该比其他变体带来性能优势,但没有办法将数组中的所有位置分配给除 undefined 之外的特定值,即当你用一个大小初始化时你会得到什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM