问题描述:

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();
}

哈哈哈!

最新文章

  1. ubuntu安装ANSYS17.2全过程
  2. BZOJ 3771: Triple
  3. *HDU1846HDU2188 巴什博奕
  4. AngularJs $q promise
  5. 《Javascript设计模式》笔记一js的表现力
  6. MSDN Kinect for Windows SDK中文版论坛开放了
  7. [Linux] 取得服务器版本
  8. Android 身份证号码查询、手机号码查询、天气查询
  9. qemu-kvm命令
  10. Web APP 随笔
  11. c# xml操作类
  12. 用ifconfig命令,只有lo,没有eth0的解决方案
  13. 4)Javascript设计模式:Decorator模式
  14. android 屏幕适配,hdpi,xhdpi,xxhdpi理解,常见出图
  15. MySQL 上手教程
  16. 网页发起qq临时会话
  17. mac 修改root密码
  18. Switch 中参数的范围探讨
  19. Apollo 启动脚本解析
  20. [转] AForge.NET 图像处理类

热门文章

  1. javascript 内置对象和方法
  2. 认识一下 RabbitMQ
  3. html恶搞之无限弹窗
  4. PHP 1-16课
  5. LeetCode 11 水池蓄水问题
  6. jQuery学习总结(三)
  7. mui html5 plus
  8. 工具 之uniq
  9. react-native---&gt;RN发送/接收事件机制
  10. composer intall 报错