What causes NaN to be displayed by parseInt function in Angular?

Currently, I am iterating through an array and adding the keys to my panels array. The length of the array is correct, totaling three elements. However, when I use parseInt on the key (which is a string), it displays NaN instead of converting it to an integer for display as panel-0, panel-1, and so on. How can I successfully convert the string key to an integer?

Object.keys(this.Category).forEach((key) => {
      this.panels.push(parseInt(key, 3));
      this.activeIds = this.panels.map(p => 'panel-' + p);
    });

Answer №1

When you execute parseInt('Car' 3), you are attempting to convert 'Car' into a number which will result in NaN.

Perhaps what you intended was the following:

Object.keys(this.Category).forEach((key) => {
   this.panels.push('panel-' + panels.length + 1);
});

Answer №2

When using the parseInt function in JavaScript, a string and a radix (between 2 and 36) are required. The function first removes any whitespace and then checks if the characters in the string represent a valid number within the specified radix range. If the initial character is not a valid number according to the radix, NaN is returned. It continues parsing character by character until a valid number is found.

For example, parseInt("-bob",36) will return -15131 in base 36. However, parseint("3",3) will result in NaN. In the case of

parseint("  1234567890", 10)
, the function will return 1234567890 after eliminating the leading white spaces.

It is important to note that the starting character of the string can affect the interpretation of the radix. Specifying the radix ensures correct parsing, especially when dealing with non-decimal numbers. Default radices can lead to unexpected behavior, such as interpreting numbers starting with 0 as octal or hexadecimal values.

For more information on the parseInt function and how it handles various scenarios, refer to Mozilla's comprehensive documentation.

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

What is causing TypeScript to incorrectly infer rest parameters in function implementation?

I have created a function that takes a string name and a varying number of parameters which should be inferred from a specific interface. While calling this function results in correct inference, the type is not narrowed down within the function itself. in ...

Angular Material - Implementing pagination for a dynamic table

I'm facing a challenge with my Angular Material dynamic table, as I am fetching data from an external database using an API. I am attempting to implement pagination on the table, but I can't seem to find suitable examples that match my scenario. ...

Get items from an array that have a property matching another array

Is there a more efficient way to create a new array with contact objects that have values matching those in selectedContact? selectedContact: number[] = [0,2] //value contacts: Contact[] = [{ firstName:"Dan"; lastName:"Chong"; email:"<a href="/c ...

Translate from one category to a different one

I often encounter a common issue - how can I efficiently convert one type to another? For instance, extending an object received from the server with UI-specific properties. interface RawData { id: number someOtherData: string } interface ViewData ex ...

When using Angular, it is important to remember that calling `this.useraccount.next(user)` may result in an error stating that an argument of type 'HttpResponse<any>' cannot be used with a 'Useraccount' balance

When attempting to use this.useraccountsubject(user) to insert information upon login, I encountered an error: ErrorType: this.useraccount.next(user) then Error An argument of type 'HttpResponse' is not allowed against a balance of 'Userac ...

Generate an auto-focus Power BI report seamlessly and effortlessly

I'm working on a straightforward Microsoft Power BI example that showcases a list of employees grouped by gender. <iframe width="300" height="200" src="https://app.powerbi.com/view?r=******" ></iframe> The issue I am facing is that the ...

Process running on an undetermined outcome (resulting from a function that requires promises to be fulfilled)

I'm feeling pretty lost when it comes to handling promises. I've been doing a lot of reading, particularly in the context of Typescript and Angular, as I'm working on fetching data from an API REST. Within my code, there's a method call ...

reinstate dummy of external class method in ts-jest

Problem I am encountering an issue while trying to mock a function that is imported from another class and called within the main class. Although I can successfully mock the function and return the specified values, I am unable to revert the mocked functi ...

Are there any events in Angular maps like ZoomShift or MoveToCenter?

Greetings, I am currently involved in a project that utilizes Angular Maps, with Angular 6 for the frontend and Python for the backend. My task at hand is to retrieve the coordinates of certain points within a defined range of kilometers from the API. The ...

Utilizing Lodash to extract properties, dividing arrays, and obtaining distinct values

I found a more effective method to accomplish the task in my JavaScript project by utilizing the Lodash library. The approach involves extracting properties, splitting arrays, and obtaining unique values. var taskobj = [ {'taskno':'a&apos ...

How to send an array of struct members to a function in C

static void fill_array(int arr[], int count, int num) { int i; for(i=0; i<count; i++) { arr[i] = num; } } typedef struct { int a[10]; } x; int main(void) { x *x1; fill_array(x1->a, 10, 0); } Upon attempting ...

Ordering in the template is a breeze

Within my template, I want to display the available hours in order. Here is an example of my template: <ul> <li class="heure" *ngFor="let heure of plageHeure" [ngClass]="{ odd: (heure%2 == 0), even: heure %2 == 1 } "> <a *ngIf ...

Every time my Canvas loads, it consistently fills up the entire width but neglects to occupy the complete height

My Canvas is only taking full width, but not full height. Here's my code snippet in an attempt to make it both full width and full height: export class AimComponent implements OnInit { @ViewChild('canvas') myCanvas: ElementRef; public ...

Advanced TypeScript deduction

I have a coding query: interface Feline{ purr:boolean } interface Jungle{ lion:Feline, tiger:Feline, leopard:Feline } later in the code: let cats:Jungle;// assume it's properly defined elsewhere for(const j in cats) if(cats.hasOwnProperty(j)){ ...

Tips for utilizing the JS attribute "offsetWidth" within Angular 4

I am attempting to retrieve the width of an element using JavaScript in my Angular application. document.getElementsByClassName("element")[0].offsetWidth; However, I keep encountering the following compilation error: Property 'offsetWidth' d ...

What is the best way to iterate through this JSON data on an Android device

Is there a way to efficiently iterate through this particular JSON array? [ { "full_name": "Abc Xyz" }, { "full_name": "Def Xyz" }, { "full_name": "Nml Xyz" }, { "full_name": "Jol Xyz" } ] Appreciate any help! ...

It appears that `ngClass` is functioning properly during the initial page load, but once the user interacts with it and the expression changes, it is

I have begun my journey into learning Angular. Recently, I came across the [ngClass] directive which allows me to add and remove multiple CSS classes dynamically. However, I encountered an issue when trying to change the color of a text based on a variable ...

Exploring the Module System of TypeScript

I am working with a TypeScript module structured like this: let function test(){ //... } export default test; My goal is for tsc to compile it in the following way: let function test(){ //... } module.exports = test; However, upon compilation, ...

Creating a submodule in Angular is a great way to organize and modular

Currently, I am developing an angular 2 app using CLI. The size of my app module is becoming too large and complex, so I have decided to create submodules. The submodule structure is as follows: // Project Submodule import { NgModule } from & ...

Create a standalone 404 page using React Router that is completely isolated from any other components

Currently, I am collaborating with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfadbabebcabbaadf2adb0aaabbaadf2bbb0b29fe9f1ebf1ed">[email protected]</a> and the code I am working on looks like this: index.tsx ...