首页 文章资讯内容详情

RGB颜色到十六进制颜色JavaScript

2026-06-04 1 花语

我们需要编写一个采用RGB颜色并返回其十六进制表示形式的JavaScript函数。

该函数应接收一个包含三个数字的对象,这些数字分别表示红色,绿色和蓝色。

例如:

rgbToHex(0, 128, 192) should return #0080C0

为此的代码将是-

const rgbColor = { red: 0, green: 51, blue: 155 } function rgbToHex({ red: r, green: g, blue: b }) { const prefix = #; const hex = prefix + ((1 << 24) + (r << 16) + (g << 8) + b) .toString(16) .slice(1); return hex; }; console.log(rgbToHex(rgbColor));

以下是控制台上的输出-

#00339b