gpt4 book ai didi

javascript - 尝试检查 Knockout Observable Array 中是否存在对象

转载 作者:行者123 更新时间:2023-12-01 03:41:06 25 4
gpt4 key购买 nike

我试图检查一个对象是否与可观察数组中具有相同可观察属性的其他对象具有相同的可观察值。

我创建了一个 foreach 循环,它评估是否有任何可观察值匹配。我遇到的问题是条件总是评估为 true,即使这些值不同。我正在使用 typescript 和 knockout 。

代码如下:

 export function addPDFToPackage(heat: MTRHeat): void {

var koHeat: MTRHeatWithInclude = ko.mapping.fromJS(heat);
koHeat.Include = ko.observable(true);

var arrayOfHeats = model.mtrPackage.Heats();
var addToHeats = () => model.mtrPackage.Heats.push(koHeat);

var duplicate = false;

arrayOfHeats.forEach(function (koHeat, i) {
if (arrayOfHeats[i].MTRID() == koHeat.MTRID() && arrayOfHeats[i].HeatID() == koHeat.HeatID() && arrayOfHeats[i].PartID() == koHeat.PartID()) {
duplicate = true;
}
else
duplicate = false;
})

if (!!model.mtrPackage.PackageID()) {
if (duplicate) {
var c = confirm("Warning: Duplicate MTR located on current package.Proceed ?")
if (c) {
ServiceMethods.addHeatToPackage(model.mtrPackage.PackageID(), heat.HeatID).done(addToHeats);
}
if (!c) {
return;
}
}
}
}

最佳答案

第一个问题:您的循环将每个对象与其自身进行比较,因为您重复使用了变量名称 koHeat。我相信您确实想引用“外部”koHeat

第二个问题:您在每次循环迭代中覆盖duplicate 变量。这可能不是您想要的。相反,您希望在发现重复项后立即停止循环。

类似的事情怎么样?

export function addPDFToPackage(heat: MTRHeat): void {
var koHeat: MTRHeatWithInclude = ko.mapping.fromJS(heat);
var packageId = model.mtrPackage.PackageID();

koHeat.Include = ko.observable(true);

function equals(a: MTRHeatWithInclude, b: MTRHeatWithInclude): boolean {
return a.MTRID() == b.MTRID() && a.HeatID() == b.HeatID() && a.PartID() == b.PartID();
}

if ( !!packageId && (
!model.mtrPackage.Heats().some(item => equals(item, koHeat)) ||
confirm("Warning: Duplicate MTR located on current package.Proceed ?")
)
) {
ServiceMethods.addHeatToPackage(packageId, heat.HeatID).done(() => {
model.mtrPackage.Heats.push(koHeat);
});
}
}

理想情况下,equals() 函数应该是 MTRHeatWithInclude 类的方法。

关于javascript - 尝试检查 Knockout Observable Array 中是否存在对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43877826/

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