我想使用chart.js
结构不完整,但这并不重要-我想。我有一个yAxes的原型结构。这些应该在chartDef.options.scales.yAxes中插入3x,但是通过值,我可以独立地更改这三个部分。并且应该插入ID。但是,就像在我的代码中一样,这三个部分都更改为相同的(最后)数字。
对我来说,这看起来像是按值添加/引用问题。
我该怎么解决呢?
谢谢
var yaxes_prototype ={
ticks: {
autoSkip: true,
maxTicksLimit: 20,
min: -1,
max: 1,
stepSize: 0.2
}
}
var chartDef = {
type: 'line',
data: {
datasets: []
},
options: {
responsive: true,
showTooltips: true,
hoverMode: 'index',
stacked: false,
scales: {
xAxes: [],
yAxes: []
},
}
}
console.log("yaxes_prototype",yaxes_prototype)
for (var i=0 ; i<3 ; i++){
//##### OK, but BY REFERENCE
chartDef.options.scales.yAxes.push(yaxes_prototype);
// OK ,insert as newobject
chartDef.options.scales.yAxes[i]["id"]=i
// key,:val was added, but all val the same
}
console.log("chartDef",chartDef.options.scales)
发布于 2022-02-03 02:32:03
问题是,您发送的yaxes_prototype
完全相同的三次。
下面的这个片段可以帮助您查看obj1
发送作为param是否被接收到完全相同的对象(通过引用),如果您更改了其中的任何一个,那么所有这些都会改变。
var obj1 = {name: "foo", value: "bar"};
(function() {
if ( typeof Object.prototype.uniqueId == "undefined" ) {
var id = 0;
Object.prototype.uniqueId = function() {
if ( typeof this.__uniqueid == "undefined" ) {
this.__uniqueid = ++id;
}
return this.__uniqueid;
};
}
})();
function printId(obj) {
console.log(obj.uniqueId());
}
for(var i=0; i<3; i++)
printId(obj1);
因此,您应该复制它并在循环中作为不同的变量/对象重新发送:
var yaxes_prototype ={
ticks: {
autoSkip: true,
maxTicksLimit: 20,
min: -1,
max: 1,
stepSize: 0.2
}
}
console.log("yaxes_prototype",yaxes_prototype)
for (var i=0 ; i<3 ; i++){
var copyObj = {...yaxes_prototype}; // This copies the value stored in yaxes_prototype
chartDef.options.scales.yAxes.push(copyObj);
// OK ,insert as newobject
chartDef.options.scales.yAxes[i]["id"]=i
// key,:val was added, but all val the same
}
https://stackoverflow.com/questions/70969098
复制