The item holds significance, but when converted to a Uint8Array, it results in being 'undefined'

Hey there! I have a Uint8Array that looks like this:

var ar = new Uint8Array();
ar[0] = 'G';
ar[1] = 0x123;

The value at the second index is a hexadecimal number, and I want to check if ar[1] is greater than zero. So I wrote this code:

if(ar[1] > 0){
  console.log("OK");
}
else{
  console.log("NOP")
}

However, when I try to output console.log(ar[1]), I get 'undefined'. Check out this simple JSBin I created.

Answer №1

In my understanding, the number of entries must be included as an argument in the constructor.

const newArray = new Uint8Array(2);
newArray[0] = 'G';
newArray[1] = 0x123;

console.log(newArray[1]);

if(newArray[1] > 0){
  console.log("All good");
}
else{
  console.log("Not okay")
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

UPDATE: Upon re-reading the documentation, it appears that you can also use the empty constructor

new Uint8Array(); // introduced in ES2017
. However, no functional example is provided.

Answer №2

To achieve this, you have the option to utilize UintArray.from() or specify the number of elements when initializing the constructor, followed by assigning values to specific indices using bracket notation

var ar = Uint8Array.from(["G", 0x123]);

if (ar[1] > 0) {
  console.log("OK");
} else {
  console.log("NOP")
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for assigning a URI as a variable based on the environment, whether it is in production or not

Seeking advice on deploying a MERN app onto Heroku. I have the mongodb URI declared in a config file locally, but on Heroku I am using process.env.mongoURI. How can I adjust my code to use the local config file when running locally and the Heroku config wh ...

Can the distinction between a page refresh and closure be identified using the method below?

My idea is to trigger a popup window when the page is closed, not when it is refreshed. The plan is as follows: Client Send an ajax request to the server every x seconds. Server var timeout=0 var sec=0 while (sec>timeout) { open popup win ...

Inquiring about the rationale behind using `jquery.ui.all.css` specifically

I'm curious about the impact of jquery.ui.all.css on Tabs As soon as I remove it, <link rel="stylesheet" href="jquery/dev/themes/base/jquery.ui.all.css"> My tabs stop functioning. Here's my query: What exactly does the jquery.ui.all.cs ...

Node.js process.exec() function allows you to asynchronously spawn a subprocess

After writing the code, I ran it and found that the terminal was unresponsive with no output, causing the program to be stuck. var util=require('util') var exec=require('child_process').exec; exec('iostat 5',function(err,stdo ...

Position the read more buttons in JavaScript at the bottom of the div

I designed three boxes in this section with content inside. To enhance the functionality, I added a feature that made the boxes smaller. Everything was functioning perfectly, but I encountered an issue with the alignment of the buttons at the bottom. Is th ...

Develop a React npm package with essential dependencies included

I have been working on developing a UI library using React ts. As part of this project, I integrated an external library called draft-js into the package. However, when I attempt to implement my library in another project, I keep encountering errors. Despi ...

How to use Express Validator to validate both email and username within a single field?

I am currently developing an application using the Express (Node.js framework) and I want to allow users to log in with either their email address or username. My question is, how can I implement validation for both types of input on the same field using e ...

Selenium is having trouble finding an element on the PayPal login page

I am currently facing an issue with automating the PayPal login page using a page object. Despite my efforts, I am unable to click on the Log In button on the page. Here is how the PayPal login page looks: https://i.sstatic.net/9RdvO.png This is my curr ...

Using Typescript to assign a new class instance to an object property

Recently, I crafted a Class that defines the properties of an element: export class ElementProperties { constructor( public value: string, public adminConsentRequired: boolean, public displayString?: string, public desc ...

Storing approximately 1 kilobyte of information throughout various pages

Is it feasible to store approximately 1kb of data while transitioning between two pages on the same domain using Javascript, Jquery (1.7), and Ajax? For instance, a user inputs data into a textbox on one page and then moves to another specific page. Can ...

Deactivate a Button until Another One is Clicked in React

Is there a way to disable the submit button until a rating has been provided? My Current State this.state = { stars: [ { active: false }, { active: false }, { active: false }, { active: false }, { active: fal ...

Converting to alphanumeric characters using JavaScript

Is there a way to efficiently encode a random string into an alphanumeric-only string in JavaScript / NodeJS while still being able to decode it back to the original input? Any suggestion on the best approach for this would be greatly appreciated! ...

% unable to display on tooltip pie chart in highcharts angular js

https://i.stack.imgur.com/Ccd7h.png The % symbol isn't displaying correctly in the highcharts ageData = { chartConfig: { options: { chart: { type: 'pie', width: 275, height: 220, marginTop: 70 ...

Error: The JQUERY autocomplete is throwing an uncaught type error because it cannot read the property 'length' of an undefined value

These scripts are being utilized at this source I have implemented jQuery Autocomplete to search for users in my database. Below is the controller code returning Json: public function searchusers1() { if ($_GET) { $query = $this -> input ...

The JSON file containing API data is stored within the _next folder, making it easily accessible to anyone without the need for security measures or a login in the Next

When accessing the protected user Listing page, we utilize SSR to call the api and retrieve all user records which are then rendered. However, if one were to check the Network tab in Chrome or Firefox, a JSON file containing all user data is generated and ...

Is it possible to modify parameter values while transitioning?

While transitioning, I need the ability to modify parameter values. After researching the documentation, I discovered a method called `params('to')` that allows accessing target state's parameters. This is how it looks in my code: $transiti ...

Guide on centering an unfamiliar element in the viewport using HTML, CSS, and JavaScript

In the process of developing my VueJS project, I have successfully implemented a series of cards on the page. However, I am now facing a challenge - when a user selects one of these cards, I want it to move to the center of the screen while maintaining its ...

disableDefault not functioning properly post-fadeout, subsequent loading, and fade-in of new content with a different URL into

After extensive searching, I still haven't found a solution to my problem. My task involves bringing in HTML pages into a div element. I managed to make the content fade out, load new href content, and then fade in the new content. However, I'm ...

Issue with Discord.js (14.1) - Message Handling Unresponsive

After developing a sizable Discord Bot in Python, I decided to expand my skills and start learning JS. Despite thoroughly studying the documentation and comparing with my original Python Bot regarding intents, I am facing difficulties getting the message ...

Discovering a specific property of an object within an array using Typescript

My task involves retrieving an employer's ID based on their name from a list of employers. The function below is used to fetch the list of employers from another API. getEmployers(): void { this.employersService.getEmployers().subscribe((employer ...