JaimeCheng / zxx-quiz-summary

zxx-quiz 小测收集总结
https://github.com/zhangxinxu/quiz
1 stars 0 forks source link

JS基础测试39 - HEX色值 #16

Open JaimeCheng opened 5 years ago

JaimeCheng commented 5 years ago

题目: js39 原issue

回答:

// 我的回答
// 1
function colorPad (str) {
  const reg = /^#?[A-Fa-f0-9]{1,6}$/g
  if (reg.test(str)) {
    str = str.replace('#', '')
    if (str.length === 1) {
      return '#' + str.repeat(6).toLowerCase()
    } else if (str.length === 2) {
      return '#' + str.repeat(3).toLowerCase()
    } else if (str.length === 3) {
      return '#' + str[0].repeat(2) + str[1].repeat(2) + str[2].repeat(2)
    } else if (str.length === 6) {
      return '#' + str.toLowerCase()
    } else {
      return '#000000'
    } 
  } else {
    return '#000000'
  }
}
// 2
var getRandomColor = function () {
  return '#' + (Math.random() * 0xffffff << 0).toString(16);
}
// 3 转10进制 ->求随机数 -> 转16进制 -> 不足6位补0
function colorRange (start, end) {
  start = parseInt(colorPad(start).split('#')[1], 16)
  end = parseInt(colorPad(end).split('#')[1], 16)
  const randomNum = Math.floor(Math.random() * (end + 1 - start) + start)
  const res = randomNum .toString(16)
  return '#' + '0'.repeat(6 - res.length) + res
}

满分回答

总结:

  1. 由于粗心没有转大小写第一题。
  2. 第三题要注意的点都答上了!

> 在线demo <

JaimeCheng commented 4 years ago

zxx: 本期要点

  1. 题目1,3测试见:http://quiz.xiliz.com/qunit39.html
  2. 常见错误算法:取范围的时候,依次取对应位数的范围,举例:'100' 和 '001' 之间范围的值,如果是错误算法,055是不可能取到的。而且'000'并不在范围之内,所以这是严重错误的算法。
  3. 常见错误2:没有补0,已经在代码那里备注了。
  4. HEX色值本质上是16进制的颜色表示方法。所以,如果我们要比对,可以转成10进制,如果要把数值变成HEX色值,直接转16进制就可以。JS自带很多方法,例如(200).toString(16) -> 'c8',注意前面补0,可以使用ES6 padStart()方法。
  5. 代码不精简没关系,算法小白也没关系,运行正确才是首位的。