R
R
Ruslan Timurziev2017-09-27 14:50:31
WordPress
Ruslan Timurziev, 2017-09-27 14:50:31

How to solve a type conversion problem when NaN gets in the way?

var someArray = ['3232', 'sdfdsf', 'gfdgdsf', '23423', '54534']
someArray.map(i => {
  if (если строка с числами) {
    // тут что-то делается
  } else if (если строка с символами) {
    // и здесь что-то делается
  }
})

In a combat task, I need to get data from json and sort it through a loop for a table. So sort in js assumes different behavior for numbers and strings. In numbers, the value is equalized, and the strings are compared by the alphabet sequence. Therefore, I need conditions (they are in the code). When we need to know whether it is a number or a string, we first of all check the type or even convert before that, which I did:
When I execute +'3223', then the output is 3223. That is, typeof +'3223' === 'number' gives true. That's good, that's what I need.
When I do +'sdfsdafew', the output is NaN. Those. typeof +'dsfadfdsa' === 'number' is true because NaN is a number, grab it by the leg!
For half an hour I compared values ​​with NaN, saying "if (+'fdsfsdf' !== NaN)"... And NaN cannot even be compared with itself, since NaN === NaN equals false...
What should I do?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mr Crabbz, 2019-06-16
@Punkie

1. Open Youtube
2. Write something like "wordpress landing"
3. Watch
4. Do it
5. Profit
Very difficult, of course, but try it.

A
Alexey Nikolaev, 2017-09-27
@RuslanTimuziyev

Check for NaN with the isNaN special function and you'll be fine. Returns true if the result is NaN, and false for any other value.

P
profesor08, 2017-09-27
@profesor08

Elementary:

var someArray = ['3232', 'sdfdsf', 'gfdgdsf', '23423', '54534']
someArray.map(i => {
  if (!isNaN(i)) {
    // делай что-то с числами
  } else {
    // делай что-то со строками
  }
})

Google is also elementary:
https://www.google.ru/search?q=js+string+is+number

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question