-2

I am trying to loop through an array and check if it contains an integar but i cant get it to work and i dont understand why. Do I have to use the map method?

My code is like this:

 let words = ['Dog', 'Zebra', 'Fish'];


    for(let i = 0; i <= words.length; i++){

        if(typeof words[i] === String){

            console.log('It does not contain any Numbers')
        }
        else{
            let error = new Error('It does contain Numbers')
            console.log(error)
        }
    } 
ulrik
  • 11
  • 3
  • 1
    `typeof "hello world"` is the string `"string"`, not `String`. – Pointy May 21 '20 at 13:28
  • Does this answer your question? [(Built-in) way in JavaScript to check if a string is a valid number](https://stackoverflow.com/questions/175739/built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number) – Józef Podlecki May 21 '20 at 13:32

6 Answers6

0

Check the words array:

words.includes(int);
Gustav Rasmussen
  • 3,720
  • 4
  • 23
  • 53
0

I am not a javascript expert but what about:

 isNaN(words[i]) 

instead of the typeof call?

I got this from a similar question here: (Built-in) way in JavaScript to check if a string is a valid number

greenbeast
  • 364
  • 2
  • 8
  • 21
0

If you just have to check if any integer there or not in array, you can make use of some method:

let words = ['Dog', 'Zebra', 'Fish'];
var result = words.some(val=>isFinite(val));
console.log(result);

some will return true or false accordingly. In this case it will be false as no numbers are present in the array.

gorak
  • 5,233
  • 1
  • 7
  • 19
0

You can use following in-build javascript function for this

isNaN(value) //It will returns true if the variable is not a valid number

Example:

isNaN('Dog') //it will return true as it is not a number
isNaN('100') //it will false as its a valid number

You can do:

isNaN(words[i])
Ashu_90
  • 904
  • 7
  • 8
0
  1. you should check for === "string"
  2. Note, that your for loop has to be < instead of <=, otherwise you would iterate it 4 times instead of 3

Your code should look like this:

    let words = ['Dog', 'Zebra', 'Fish'];

    for (let i = 0; i < words.length; i++) {
      if (typeof words[i] === "string") {
        console.log('It does not contain any Numbers')
      } else {
        let error = new Error('It does contain Numbers')
        console.log(error)
      }
    } 
0

Here is my contribution to a possible solution:

let arr = ["Susan", "John", "Banana", 32];

// Option 1
arr.map(item => typeof item)

// Option 2
arr.map(item => console.log("Array item: ", item, "is a", typeof item))

// Option 3
arr.map(item => {
    if(typeof item === "string") {
        console.log("Item is a string");
    } else {
        let error = new Error("Item contains numbers")
        console.error(`%c${error}`, "color: red; font-weight: bold" );
    }
})
Stephan Du Toit
  • 789
  • 1
  • 7
  • 19