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

Comparing an object to the previous one in the array

本文关键字:一个对象 比较 数组      更新时间:2023-09-26

午后堆栈,

我对JS和淘汰赛比较陌生,我想我遇到了一个简单的问题。我正试图将术语从每个类中分离出来,并相应地分组。

确实可以Adv Cptr架构(CPHE-533-A)

W14

Adv数据库系统(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 -->

Javacript:

<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,并且当您使用!==时,比较返回始终为真。

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

代替

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

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

在您的比较中,尝试更改:

getTerm($parent.myclasses.Classes()[$index()-1].FullName)

:

getTerm($parent.myclasses.Classes()[$index()-1].FullName())

你需要在FullName中添加括号,这样它就可以调用可观察对象来获取值。你在左边做了,但是在右边没做。