gpt4 book ai didi

javascript - 每个对象的 RGB 映射

转载 作者:行者123 更新时间:2023-12-02 16:10:53 25 4
gpt4 key购买 nike

我有 javascript 对象,其中包含 8 个对象。每个物体都会有其对应的颜色信息。有没有办法用 RGB 颜色映射每个对象?

输入

myData[{a:29},{a:17},{a:26},a{19},a{18},a{40},a{89},a{14}];

输出:

myData[{a:29, color:#RGB},{a:17, color:#RGB},....];

最佳答案

一种方法:

function insertAt(ary, item, at) {
ary.splice(at, 0, item);
}

function addColors(data, hue) {
var dataWithColors = [];
var highest = data[0].a;
for (var i = 1; i < data.length; i++) {
if (data[i].a > highest) {
highest = data[i].a;
}
}
var lowest = data[0].a;
for (var i = 1; i < data.length; i++) {
if (data[i].a < lowest) {
lowest = data[i].a;
}
}
var hueIndexes = {red: 0, green: 1, blue: 2};
var range = highest - lowest;
for (var i = 0; i < data.length; i++) {
var value = data[i].a;
var absInRange = value - lowest;
var shade = Math.round(0xff - (0xff * absInRange / range));
var subStr = shade.toString(16);
if (subStr.length == 1) {
subStr = "0" + subStr;
}
var color = ["00", "00"];
insertAt(color, subStr, hueIndexes[hue]);
var str = "#" + color.join("");
dataWithColors.push({a: value, color: str});
// (Alternative: eg https://lodash.com/docs#assign .)
}
return dataWithColors;
}

var sample = [{a:29},{a:17},{a:26},{a:19},{a:18},{a:40},{a:89},{a:14}];
var sampleWithColors = addColors(sample, "green");

console.dir(sampleWithColors);
/* [
{a: 29, color: "#00cc00"},
{a: 17, color: "#00f500"},
{a: 26, color: "#00d600"},
{a: 19, color: "#00ee00"},
{a: 18, color: "#00f100"},
{a: 40, color: "#00a700"},
{a: 89, color: "#000000"},
{a: 14, color: "#00ff00"}
] */

关于javascript - 每个对象的 RGB 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30221123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com