gpt4 book ai didi

JavaScript 循环/数组

转载 作者:行者123 更新时间:2023-11-29 16:41:01 25 4
gpt4 key购买 nike

我有简单的 javascript 代码,下面我使用 SimpleJSON java api 从 JSON 数组对象进行初始化,如何在循环内设置 data=dataSets[i] 而不是对其进行硬编码。

var scatterChart = new Chart(ctx, {
type : 'scatter',
data : {
datasets : [
{
borderColor : window.chartColors.red,
backgroundColor : color(window.chartColors.red)
.alpha(0.2).rgbString(),
label : 'Sample1'
data : dataSets[0]

},
{

data : dataSets[1]

},
{
borderColor : window.chartColors.blue,
backgroundColor : color(window.chartColors.blue)
.alpha(0.2).rgbString(),

data : dataSets[2]
},

{
data : dataSets[3]
}, {
data : dataSets[4]
}, {
data : dataSets[5]
}, {
data : dataSets[6]

}, {
data : dataSets[7]
}, {
data : dataSets[8]
}, {
data : dataSets[9]
}, {
data : dataSets[10]

} ]`

最佳答案

您还可以将数据集映射到对象数组,其中数据集是数据属性,然后您可以使用一些额外的属性扩展第一个和第三个:

// transform the datasets (from the api?) to the structure that you want
var dataSetsWithData = dataSets
.map(dataSet => ({ data: dataSet})) ;
// you now have an array of objects

// manually add the extra properties for the ones you're intresed in
dataSetsWithData[0] = {
// keep the original properties, in this case just "data"
...dataSetsWithData[0],
// additional properties for this particular index
borderColor : window.chartColors.red,
backgroundColor : color(window.chartColors.red)
.alpha(0.2).rgbString(),
label : 'Sample1'
};

dataSetsWithData[2] = {
// keep the original properties, in this case just "data"
...dataSetsWithData[0],
// additional properties for this particular index
borderColor : window.chartColors.blue,
backgroundColor : color(window.chartColors.blue).alpha(0.2).rgbString(),
};

var scatterChart = new Chart(ctx, {
type : 'scatter',
data : {
datasets : dataSetsWithData
}
});

关于JavaScript 循环/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45817343/

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