javascript - 为什么javascript表现出奇怪的行为?
问题描述
我在java中试过这段代码可以正常工作,但是在切换javascript时它不能正常工作。
function checkNumberIfContainsKey(number, key){
while(number > 0){
if(number%10 == key){
return true;
}
number /= 10;
}
return false;
}
console.log(checkNumberIfContainsKey(19, 9));
console.log(checkNumberIfContainsKey(191, 9));
console.log(checkNumberIfContainsKey(912, 9));
console.log(checkNumberIfContainsKey(854, 9));
如果此函数在任何位置包含键,则该函数应返回 true。示例:checkNumberIfContainsKey(19, 9) 输出:true
my expected output:
checkNumberIfContainsKey(19, 9) //true
checkNumberIfContainsKey(191, 9) //true
checkNumberIfContainsKey(912, 9) //true
checkNumberIfContainsKey(185, 9) //false
my output:
checkNumberIfContainsKey(19, 9) //true
checkNumberIfContainsKey(191, 9) //false
checkNumberIfContainsKey(912, 9) //false
checkNumberIfContainsKey(185, 9) //false
解决方案
像这样使用它
function checkNumberIfContainsKey(number, key){
var a = !!number.toString().match(key)
console.log(a)
return a;
}
checkNumberIfContainsKey(19, 9) //true
checkNumberIfContainsKey(191, 9) //true
checkNumberIfContainsKey(912, 9) //true
checkNumberIfContainsKey(185, 9) //false
推荐阅读
- c++ - 为什么不接受使用概念的此类专业化?
- graphql - 如何从 Nuxt 前端访问经过身份验证的 GraphQL API
- mysql - 如何使用 ONE single QUERY 从 mysql 中的另一个表中查找不存在的值
- typescript - 限制nestjs的API速率
- javascript - 当我重置状态时,进度条重新呈现以前的状态
- c - Windows 上的 MinGW Make 命令找不到 -lncurses
- python - Pandas 数据框的转换
- postgresql - 在 PostgreSQL 中使用 null 值取消透视
- java - 未知实体:java.lang.String
- mysql - 如何在 my.cnf 中设置 optimizer_switch='block_nested_loop=off'