function sevenBoom(arr) {
if (arr.includes(7)) {
return "Boom!"
}
return "there is no 7 in the array"
}
测试
Test.assertEquals(sevenBoom([2, 6, 7, 9, 3]), "Boom!")
Test.assertEquals(sevenBoom([33, 68, 400, 5]), "there is no 7 in the array")
Test.assertEquals(sevenBoom([86, 48, 100, 66]), "there is no 7 in the array")
Test.assertEquals(sevenBoom([76, 55, 44, 32]), "Boom!")
Test.assertEquals(sevenBoom([35, 4, 9, 37]), "Boom!")
最后 2 个测试失败了,我假设是这种情况,因为它正在寻找
7
,而不仅仅是在数字本身中有一个 7
。我怎么能纠正这个?
不是重复的
这与子字符串或字符串无关。为什么人们如此喜欢将事物标记为重复?
最佳答案
没有正则表达式的解决方案:
function sevenBoom(arr) {
for(let el of arr) {
if(el.toString().split('').includes('7')) {
return "Boom!"
}
}
return "there is no 7 in the array"
}
console.log(sevenBoom([2, 6, 7, 9, 3], "Boom!"))
console.log(sevenBoom([33, 68, 400, 5], "there is no 7 in the array"))
console.log(sevenBoom([86, 48, 100, 66], "there is no 7 in the array"))
console.log(sevenBoom([76, 55, 44, 32], "Boom!"))
console.log(sevenBoom([35, 4, 9, 37], "Boom!"));
关于javascript - 查找数组中是否存在数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58195031/