codewars--js--RGB To Hex Conversion

问题描述:

The rgb() method is incomplete. Complete the method so that passing in RGB decimal values will result in a hexadecimal representation being returned. The valid decimal values for RGB are 0 - 255. Any (r,g,b) argument values that fall out of that range should be rounded to the closest valid value.

The following are examples of expected output values:

rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3

我的思路:

这道题做法很简单,主要就是通过toString(n)将10进制转换成16进制(注意,n的取值范围是2~36)。但是自己的写法就比较直接,很是繁琐,看到大神们的写法真是简洁。尤其是slice、map用法,拍案叫绝。

我的答案:

function rgb(r, g, b){
  // complete this function
  r=a(r);g=a(g);b=a(b);
  r=r.toString(16).toUpperCase();
  g=g.toString(16).toUpperCase();
  b=b.toString(16).toUpperCase();
  var c=r.concat(g).concat(b);
  if(c=="000"){return "000000";}
  else{return c;}
}
function a(n){
  if(n>255){return n=255;}
  if(n<0){return n=0;}
  if(n>=0 && n<=255){return n;}
}

优秀答案:

(1)

function rgb(r, g, b){
  return toHex(r)+toHex(g)+toHex(b);
}

function toHex(d) {
    if(d < 0 ) {return "00";}
    if(d > 255 ) {return "FF";}
    return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()  //slice(-2)作用若为0,则返回00;若为255,则返回ff
}

(2)

function rgb(r, g, b){
  return [r,g,b].map(function(x) {
    return ('0'+Math.max(0, Math.min(255, x)).toString(16)).slice(-2);  //将<0或>255的分别置为0或255.
  }).join('').toUpperCase();
}

哈哈哈!

原文地址:https://www.cnblogs.com/hiluna/p/8880356.html