[英]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?
我必须使用 map 方法吗?
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:我不是 javascript 专家,但是呢:
isNaN(words[i])
instead of the typeof call?而不是 typeof 调用?
I got this from a similar question here: (Built-in) way in JavaScript to check if a string is a valid number我从一个类似的问题中得到了这个: (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:如果您只需要检查数组中是否存在任何 integer ,您可以使用
some
方法:
let words = ['Dog', 'Zebra', 'Fish']; var result = words.some(val=>isFinite(val)); console.log(result);
some
will return true
or false
accordingly. some
会相应地返回true
或false
。 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您可以为此使用以下内置 javascript function
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])
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" );
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.