gpt4 book ai didi

javascript - 将一个对象与数组中的前一个对象进行比较

转载 作者:行者123 更新时间:2023-12-02 17:22:23 26 4
gpt4 key购买 nike

下午堆栈,

我对 JS 和 knockout 相对较新,我认为我遇到了一个简单的问题。我试图将每个类别中的术语分开并相应地对它们进行分组。

W13

高级 Cptr 架构 (CPHE-533-A)

W14

高级数据库系统 (CPTR-521-A)

背景中的物体是

"Classes": [
{
"FullName":"W13 Adv Cptr Architecture (CPHE-533-A)",
--Irrelevant information
},
{
"FullName": "W14 Adv Database Systems (CPTR-521-A)",
--Irrelevant information
}
]

我的 knockout 电话是

 <ul class="myclasses-container" data-bind="foreach: myclasses.Classes">
<!-- ko if: $index() === 0 -->
<p style="font-weight: bold; font-size:16px" data-bind= "text: getTerm(FullName())"></p>
<!-- /ko -->
<!-- ko if: $index() !== "0" -->
<!-- I think this is the line of code that is giving me trouble -->
<!-- ko if: (getTerm(FullName()) != getTerm($parent.myclasses.Classes()[$index()-1].FullName)) -->
<p style="font-weight: bold; font-size:16px" data-bind= "text: getTerm(FullName())"></p>
<!-- /ko -->
<!-- /ko -->

Java 脚本:

<script>
function getTerm(name) {
return name.substring(0, name.indexOf(' '));
}
function nameWithoutTerm(name) {
return name.substring(name.indexOf(' ') + +1);
}
</script>

渲染的 HTML:

 <ul class="myclasses-container" data-bind="foreach: myclasses.Classes">
<!-- ko if: $index() === 0 -->
<p style="font-weight: bold; font-size:16px" data-bind= "text: getTerm(FullName())"> W13</p>
<!-- /ko -->
<!-- ko if: $index() !== "0" -->
<!-- ko if: (getTerm(FullName()) != getTerm($parent.myclasses.Classes()[$index()-1].FullName())) -->
<p style="font-weight: bold; font-size:16px" data-bind= "text: getTerm(FullName())"></p>
<!-- /ko -->
<!-- /ko -->

如您所见,如果前一个学期不同,我要做的就是循环遍历数组打印学期;但是只显示的是 “W13”而不是“W14”。

最佳答案

正如 Patrick Steele 所说,如果它是可观察的,则需要在 FullName 中添加括号。

但是这里还有另一个问题。在第一次检查中,您将 $index()0 进行比较,这看起来不错。

问题出在您的第二次检查时,您与 "0" 而不是 0 进行比较,并且当您使用 !== 时比较总是返回 true。

所以它在第一个循环中失败,因为在检查之后,您尝试访问项目编号 $index()-1 ,其中 $index() 返回 0 意味着您正在尝试达到商品编号-1!

替换

<!-- ko if: $index() !== "0" -->

<!-- ko if: $index() !== 0 -->

关于javascript - 将一个对象与数组中的前一个对象进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23812085/

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