How do I initialize a Uint8Array?
Asked Answered
P

3

8

I want to create a Uint8Array with 8 elements. I tried this

var myarr = new Uint8Array(255,255,255,255,40,92,143,2);

but when I run

myarr.length

I get back "255" when I expect the answer would be "8". I assume I'm doing somethign wrong in my intitialization step but don't know what that is.

Pascale answered 5/6, 2018 at 19:5 Comment(0)
T
15

The different constructors are:

new TypedArray(); // new in ES2017
new TypedArray(length);
new TypedArray(typedArray);
new TypedArray(object);

So when you do

new Uint8Array(255)

It will take it as a length. However you can pass an object (an array) instead which will be iterated to create the uint array:

new Uint8Array([255, 255, /*..*/]);
Tradesfolk answered 5/6, 2018 at 19:9 Comment(0)
P
3

You need to add brackets to the list inside the Uint8Array argument

let myarr = new Uint8Array([1,2,3,...])

Print answered 5/6, 2018 at 19:8 Comment(0)
L
0

You can initialize a UintArray with a regular array like this:

const arr = [255,255,255,255,40,92,143,2]
const uintarr = new Uint8Array(arr)
console.log(uintarr.length)
Lynden answered 5/6, 2018 at 19:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.