![](/img/trans.png)
[英]Javascript: How do I check if an array contains exactly another array?
[英]How do i check if an array contains integar
我试图遍历一个数组并检查它是否包含一个整数,但我无法让它工作,我不明白为什么。 我必须使用 map 方法吗?
我的代码是这样的:
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)
}
}
检查单词数组:
words.includes(int);
我不是 javascript 专家,但是呢:
isNaN(words[i])
而不是 typeof 调用?
我从一个类似的问题中得到了这个: (Built-in) way in JavaScript to check if a string is a valid number
如果您只需要检查数组中是否存在任何 integer ,您可以使用some
方法:
let words = ['Dog', 'Zebra', 'Fish']; var result = words.some(val=>isFinite(val)); console.log(result);
some
会相应地返回true
或false
。 在这种情况下,它将是错误的,因为数组中没有数字。
您可以为此使用以下内置 javascript function
isNaN(value) //It will returns true if the variable is not a valid number
例子:
isNaN('Dog') //it will return true as it is not a number
isNaN('100') //it will false as its a valid number
你可以做:
isNaN(words[i])
您的代码应如下所示:
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) } }
这是我对可能解决方案的贡献:
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.