我试图循环检查一个数组并检查它是否包含一个integar,但我不能让它工作,我不明白为什么。我必须使用map方法吗?
我的代码是这样的,我想在数组中循环并检查是否包含一个integar,但我不能让它工作,我不明白为什么。
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专家 但如果用typeof调用来代替呢?
isNaN(words[i])
取代typeof调用呢?
我从这里的一个类似问题中得到了这个。(内置的)JavaScript中检查字符串是否为有效数字的方法。
如果你只需要检查数组中是否有整数,你可以使用 some
方法。
let words = ['Dog', 'Zebra', 'Fish'];
var result = words.some(val=>isFinite(val));
console.log(result);
some
将返回 true
或 false
相应地,在这种情况下,它将为假,因为数组中没有数字。在这种情况下,它将为false,因为数组中没有数字存在。
你可以使用下面的内置javascript函数来实现这个功能。
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" );
}
})