2017-09-16 5 views
3

StackOverflow 주제 중 하나에 따라 내가 자신의 RGB에서 16 진수로 변환기를 만들려고했습니다.RGB로 변환 HEX 문제

이유는 모르지만 그 대신 RGB 값을 두 번 변환합니다.

입력이 rgb(0, 128, 192) 일 때 #00128192을 콘솔합니다.

내 코드는 : I 기능을 실행할 준비

fromRGB: { 
    toHEX: { 
     supportFunc: function(number) { 
      var hex = number.toString(16); 
      return hex.length == 1 ? '0' + hex : hex; 
     }, 
     convert: function(r, g, b) { 
      var lol = '#' + this.supportFunc(r) + this.supportFunc(g) + this.supportFunc(b); 
      console.log(lol); 
     } 
    }, 
    prepareAndExecute: function(color_field) { 
     // preparing 
     var numbers = color_field.match(/\d+/g); 
     if(numbers.length == 3) { 
      this.toHEX.convert(numbers[0], numbers[1], numbers[2]); 
     } else { 
      alert('wrong RGB number format'); 
     } 


     //this.toHSL(preparedValue); 
    } 
} 

, lol 변수해야는 HEX 포맷 변환을 포함하는 색이다.

내 코드에 어떤 문제가 있습니까? 왜 작동하지 않는 겁니까?

+1

'.match)'는 숫자가 아닌 ** 문자열 **의 배열을 반환합니다. – Pointy

+0

[RGB to Hex and Hex to RGB]의 가능한 복제본 (https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb) –

+0

@KenWhite OP가 이미 복제본으로 사용 된 것 같습니다. 링크를 클릭하여 위의 코드를 작성하십시오. 그러나 그는 값을 얻는 방법과 관련이없는 문제 (숫자로 된 문자열)가 발생했습니다. 따라서 해당 링크를 중복으로 표시하는 것은 잘못된 것입니다. –

답변

1

설명 : supportFunc에 문자열이 아닌 숫자를 통과하고 있기 때문에

그것입니다.

prepareAndExecutematch에서의 결과는 당신이 그대로 문자열을 반환 (되지 Number.prototype.toString) String.prototype.toString 호출된다 supportFunctoString에 따라서 호출 될 때, 스트링의 배열이다.

솔루션 :

var hex = Number(number).toString(16);      // using Number to convert a string to a number (you can use parseInt or unary + if you like) 

또는 convert에 전달하기 전에 변환 :supportFunc에서

, toString를 사용하기 전에 숫자로 number 변환 (

this.toHEX.convert(+numbers[0], +numbers[1], +numbers[2]); // using unary +