[英]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.