javascript - 查找数组中是否存在数字

标签 javascript arrays

Create a function that takes an array of numbers and return "Boom!" if the number 7 appears in the array. Otherwise, return "there is no 7 in the array".

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/

相关文章:

java - 打印数组元素的索引 : Java

arrays - Int 的 Swift 3 二维数组

javascript - 如何在 PHP 的字符串 echo 中使用 window.open ?

javascript - 如何在不使用 for 循环的情况下使用迭代器对数组值求和

javascript - 显示带有到房间的路线跟踪绘制路径的室内建筑 map

python - 如何在 Python 3.3.5 中添加矩阵的对角线

arrays - 对对象数组中的多个属性求和

javascript - While 循环检查字符串中的大写字母

javascript - 如何从数组中删除除第一个元素之外的所有元素

javascript - 在javascript中展平嵌套对象