Javascript 每个数组元素的随机背景色

Javascript 每个数组元素的随机背景色,javascript,jquery,Javascript,Jquery,我正在使用它生成随机颜色: var rand = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')'; 我正在映射数据: var mappedData = data.data.map(function(item){

我正在使用它生成随机颜色:

var rand = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
我正在映射数据:

var mappedData = data.data.map(function(item){    

    return { value: item[1], name: item[0], color: rand };
);
之后,它被传递到图表

但是它用一种颜色生成整个图表。如何为每个图表元素显示此更改

我尝试添加
var bgColor=rand在mappedData中,然后将其分配给
color:bgColor
,但它给出了相同的结果

似乎您没有为
map
中的每个项目创建
rand

试试这个:

var mappedData = data.data.map(function(item) {
    var rand = 'rgb(' + (Math.floor((256 - 199) * Math.random()) + 200) + ',' + (Math.floor((256 - 199) * Math.random()) + 200) + ',' + (Math.floor((256 - 199) * Math.random()) + 200) + ')';
    return {value: item[1], name: item[0], color: rand};
});

您需要提供更多的代码。从您正在展示的内容来看,您已经为兰德指定了一种颜色。你在哪里迭代你的数组?试试这个:
var-mappedData=data.data.map(函数(项){var-rand='rgb++(Math.floor((256-199)*Math.random())+200++,'+(Math.floor((256-199)*Math.random())+200++,'+(Math.floor((256-199)*Math.random())+200)+';返回{value:item[1],name:item[0],color:rand};});。您可能没有为每个项目创建
rand
!最后一行缺少一个
}
})@RayonDabre键入该答案。从我看到的情况来看,您的rand变量超出了范围,并且只初始化了一次。您可以预先计算一组随机颜色,或者只将随机发生器放在data.data.map函数中,如下所示:var mappedData=data.data.map(函数(项){var rand='rgb(+)(Math.floor((256-199)*Math.random())+200++,'+(Math.floor((256-199)*Math.random())+200++(Math.floor((256-199 Math.random())+200)+');返回{value:item[1],name:item[0],color:rand};});