首页 > 解决方案 > 为什么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

标签: javascript

解决方案


像这样使用它

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


推荐阅读