简体   繁体   中英

Why is parseInt displaying Nan? - Angular

I am currently iterating through an array and adding the key to my panels array. I am getting the correct length of the array which is three but my parseint is displaying NaN. How can I convert the key which is a string to an int to display panel-0 for example instead of panel-NaN.

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

what you are doing is parseInt('Car' 3) , since "Car" is not a number you will get NaN

probaby you want something like this:

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

Parseint takes a string and a number between 2,36 (including both ends) called a radix. It eliminates all whitespace and then starts asking "is this number between 0-(radix-1)"? If the first character it finds, after it's out of whitespace, isn't what it considers to be a number, that's one of two conditions when it will spit out a NaN. It then evaluates character by character till it finds a number. parseInt("-bob",36) will give an integer equal to -bob base 36 (aka -15131). parseint("3",3) will give you NaN. parseint(" 1234567890", 10) gives 1234567890.

Your example is drawing off a key. Without knowing what the key is it might start with invalid characters . But, assuming you've done your due diligence and cleaned up the data. You're also asking the data to be a number base 3. The initial character can sometimes determine the base when you rely on a default radix. If you firmly want numbers between 0-9 (everyday base ten numbers) you ought to put in 10 as the second argument. If you don't put the radix in yourself, it might decide a number starting with 0 is in base 8 or 16 depending on the operating environment.

Mozilla's documentation describes the behavior in detail as well as edge cases and work arounds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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