gpt4 book ai didi

javascript - 数组(推-对象)未按预期工作

转载 作者:行者123 更新时间:2023-12-02 23:15:06 25 4
gpt4 key购买 nike

我在将对象插入数组时遇到问题。我设置了一个带有值的对象并将它们推送到数组中。然后,我更改对象的一些值并将对象再次插入数组中。但是,经过检查,插入数组的两个对象是相同的,两个对象的值都与插入数组的最后一个对象相同。

let ProductPosition = function (x, y) {
this.x = x;
this.y = y;
}

let PalletType = (function () {
function PalletType() {
this.PatternType = '';
this.ProductWidth = 0;
this.PalletWidth = 0;
this.ProductPositions = [];
}
});

function getPalletPositions(pallet, pattern) {
pal.ProductPositions = [];
let posn = new ProductPosition();
switch (pattern) {
case '1U1':
posn = [];
posn.y = pal.PalletWidth / 2;
posn.angle = 0;
posn.apprDir = 0;
pallet.ProductPositions.push(posn);
break;
case '2U1':
posn = [];
posn.y = pal.PalletWidth / 2 + pal.ProductWidth / 2;
console.log('y pos 0 ' + posn.y);
pal.ProductPositions.push(posn);//first push

posn.y = pal.PalletWidth / 2 - pal.ProductWidth / 2;
console.log('y pos 1 ' + posn.y);
pallet.ProductPositions.push(posn);//first push
break;
}
}
let pal = new PalletType();

pal.PalletWidth = 1165;
pal.ProductWidth = 400
let pat = '2U1';

getPalletPositions(pal, pat);

pal.ProductPositions.forEach(function (pos) {
console.log("pos.y:" + pos.y);
});

实际输出:

y pos 0 782.5 <-value of y of first push
y pos 1 382.5 <-value of y of second push
pos.y:382.5 <-should be 782.5
pos.y:382.5

我期望:

y pos 0 782.5 <-value of y of first push
y pos 1 382.5 <-value of y of second push
pos.y:782.5
pos.y:382.5

我完全困惑并尝试了一些方法,但无济于事。

最佳答案

您正在改变可以使用的对象 spread运算符或Object.assign

检查下面

let ProductPosition = function (x, y) {
this.x = x;
this.y = y;
}

let PalletType = (function () {
function PalletType() {
this.PatternType = '';
this.ProductWidth = 0;
this.PalletWidth = 0;
this.ProductPositions = [];
}
});

function getPalletPositions(pallet, pattern) {
pal.ProductPositions = [];
let posn = new ProductPosition();
debugger;
switch (pattern) {
case '1U1':
posn = [];
posn.y = pal.PalletWidth / 2;
posn.angle = 0;
posn.apprDir = 0;
pallet.ProductPositions.push(posn);
break;
case '2U1':
posn = [];
posn.y = pal.PalletWidth / 2 + pal.ProductWidth / 2;
console.log('y pos 0 ' + posn.y);
pal.ProductPositions.push({...posn});//first push

posn.y = pal.PalletWidth / 2 - pal.ProductWidth / 2;
console.log('y pos 1 ' + posn.y);
pallet.ProductPositions.push({...posn});//first push
break;
}
}
let pal = new PalletType();

pal.PalletWidth = 1165;
pal.ProductWidth = 400
let pat = '2U1';

getPalletPositions(pal, pat);

pal.ProductPositions.forEach(function (pos) {
console.log("pos.y:" + pos.y);
});

关于javascript - 数组(推-对象)未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57196359/

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