简体   繁体   English

为什么这个 function 不替换关联数组中的现有值 - Angular

[英]Why doesn't this function replace the existing value in the associative array - Angular

I've made sure to import my interface:我确保导入我的界面:

import { DayMoodModel } from '../objectModels/dayMood'; 

I initialized the array of objects with some test data (the date property has the type Date, in case you're wondering):我用一些测试数据初始化了对象数组(date 属性的类型为 Date,以防您想知道):

  moodsAssigned: DayMoodModel[] = [
    { 
      date: this.today,
      mood: 'great'
    }
  ]

This is the function in question:这是有问题的 function:

  addMood(moodName: string) {
    let obj: DayMoodModel = { date: this.currentDay, mood: moodName };
    for(let i = 0; i < this.moodsAssigned.length; i++) {
      if(this.moodsAssigned[i].date == this.currentDay) {
        this.moodsAssigned[i].mood = moodName;
      }
      else if(i == this.moodsAssigned.length - 1 && this.moodsAssigned[i].date != this.currentDay) {
        this.moodsAssigned.push(obj);
      }
    }
    console.log(this.moodsAssigned);
  }

When called, on a date that's already in the array of objects, it acts like that data isn't already in there for that date.调用时,在对象数组中已经存在的日期上,它的行为就像该日期的数据不存在一样。 I'll include a photo of the console log at the bottom of the post.我将在帖子底部附上控制台日志的照片。 In this test I called the function on the date that is already in the array, expecting it to replace the 'mood' value with the new mood, but it just added a new object to the array.在这个测试中,我在数组中已经存在的日期调用了 function,期望它用新的心情替换“心情”值,但它只是在数组中添加了一个新的 object。

I've gone over this code multiple times, logging out variables at key places to ensure it's reading everything correctly.我已经多次检查此代码,在关键位置注销变量以确保它正确读取所有内容。 I don't know what's wrong with the logic..不知道逻辑有什么问题。。

picture of the array logged to the console记录到控制台的阵列图片

The problem is you're trying to compare two complex objects, yet you only care about the day, month, and year.问题是你试图比较两个复杂的对象,但你只关心日、月和年。 Just a straight == isn't going to work.只是一个直接的==是行不通的。

Here is a proper comparison function from another question: How to tell if two dates are in the same day or in the same hour?这是另一个问题的正确比较 function: 如何判断两个日期是在同一天还是在同一小时?

function sameDay(d1, d2) {
  return d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM