JavaScript RGB字符串(`rgb(r, g, b)`)到HEX(`#rrggbb`)的转换。

问题描述 投票:0回答:2

componentToHex 函数在第一个组件上运行良好 r但对于其他两个组成部分,。gb但是,它并没有像预期的那样工作,ComponentToHex函数对第一个值r有效,而对其他值g和b无效。

let componentToHex = (val) => {
  const a = val.toString(16);
  return a.length === 1 ? "0" + a : a;
};

let rgbToHex = (rgb) => {
  const hex = rgb.replace("rgb(", "").replace(")", "").split(",");
  const r = hex[0];
  const g = hex[1];
  const b = hex[2];

  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

console.log(rgbToHex ('rgb(1,255,148)'));
javascript hex rgb
2个回答
1
投票

你想要的是数字部分(即 val)是一个 数目 呼叫前 toString 上。如果它是一个 绳子 当你打电话 toString 上,它将保持原样。

let componentToHex = (val) => {
  const a = Number(val).toString(16);
  //        ^^^^^^^^^^^
  return a.length === 1 ? "0" + a : a;
}
let rgbtohex = (rgb) => {
  return '#' + rgb
    .match(/\d+/g)
    .map(componentToHex)
    .join('');
}


console.log(rgbtohex('rgb(1,255,148)'));

还要注意的是,在使用变量之前,你应该先声明变量(否则在严格模式下会抛出错误,或者它们会被隐式全局化,从而导致错误)。

如上图所示,通过匹配数字字符,可以使接收和转换输入数字的函数更加优雅,映射为 componentToHex,然后再加入。


1
投票

你忘了将组件转换为 number所以你把它们当作 stringcomponentToHex,它期待的是 number.

作为 String.prototype.split() 会给你3 string在这种情况下,你可以使用 Array.prototype.map()Number() 来轻松解析所有3个问题。

function componentToHex(c) {
  // This expects `c` to be a number:
  const hex = c.toString(16);

  return hex.length === 1 ? `0${ hex }` : hex;
}

function rgbToHex(rgb) {
  // .map(Number) will convert each string to number:
  const [r, g, b] = rgb.replace('rgb(', '').replace(')', '').split(',').map(Number);
  
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}


console.log(rgbToHex('rgb(1,255,148)'));

0
投票

试试这个

let componentToHex = (val) => {
  a = Number(val).toString(16);
  return a.padStart(2, '0');
};

let rgbtohex = (rgb) => {
  hex = rgb.slice(4, -1).split(',');
  return hex.reduce((a, b) => a + componentToHex(b), '#');
};

rgbtohex('rgb(1,255,148)');

(经过修改使其更短)

© www.soinside.com 2019 - 2024. All rights reserved.