简体   繁体   中英

How do i check if an array contains integar

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)
        }
    } 

Check the words array:

words.includes(int);

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

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.

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])
  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) } }

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" );
    }
})

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