如何使用 map 函数在数据集下拥有 3 个数组,而不是另一个名为“标签”的对象。当我尝试将 map 函数放在“label”之前,就在构造函数中的“dataset”之后时,我遇到了关于出现意外“.”的奇怪错误。点等
预期输出
{
colors: blue,
datasets: [
{
label: 'car',
type: 'line',
data: '1'
},
{
label: 'bus',
type: 'line',
data: '5'
},
{
label: 'train',
type: 'line',
data: '10'
}
]
}
function Constructor(colors, label, type, data) {
this.colors = colors;
this.label = label;
this.type = type;
this.data = data;
this.mainData = {
colors: colors,
datasets: [{
label: label.map((label, i) => ({
type: type,
data: data[i]
}))
}]
}
};
var whyYouNoWork = new Constructor('blue', ['car', 'bus', 'train'], 'line', ['1', '5', '10']);
console.log(whyYouNoWork.mainData);
最佳答案
您可以使用函数 map
构建所需的输出:
function Constructor(colors, label, type, data) {
this.colors = colors;
this.label = label;
this.type = type;
this.data = data;
this.mainData = { colors, datasets: label.map((label, i) => ( { label, type, data: data[i] } ) ) }
};
var whyYouNoWork = new Constructor('blue', ['car', 'bus', 'train'], 'line', ['1', '5', '10']);
console.log(whyYouNoWork.mainData);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何在对象构造函数中使用 Map 数组函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49432237/