判断a是否等于1,2,5,6,7,9等多个数字时,有没有什么好的写法?

新手上路,请多包涵

判断一个值是否等于多个数字时有没有什么好的写法
还是说只能 == 1 && ==2 && ==5 && ==6 && ==7 && ==9这样写

阅读 2.9k
3 个回答

预先保存合法值,然后查

  1. 小范围可以用数组

    boolean[] values = new boolean[]{false, true, false};
    
    
    if (values[n]) {
     // xxx
    };
  2. 否则用Set

    Set<Integer> hashSet = new HashSet<>();
    hashSet.putAll(Arrays.asList(1, 3, 5, 7));
    
    if (hashSet.contains(n)) {
     //xxx
    }

看下js数组的includes方法是否符合需求

function compareNum(num){
const baseNumArr = [1,2,5,6,7,9];
if(baseNumArr.includes(num)){
  return true;
}else {
  return false;
}
}

compareNum(1);
const includes = n => '125679'.match(n);

以上只是开个玩笑,正常人会用数组:

const includes = n => [1, 2, 5, 6, 7, 9].includes(n);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题