Свойство Arrays Objects имеет значение true или false, но всегда становится ложным при доступе в цикле - PullRequest
0 голосов
/ 21 февраля 2020

Я столкнулся с неожиданной ситуацией. У меня есть несколько объектов (массив). Те имеют свойство break, то есть boolean. Значение break зависит от ситуации, но всегда становится ложным при сравнении в выражении if, в for или for of l oop. Я попытался изменить стиль if, используя ==, === и только свойство, но все они дают один и тот же результат, даже когда некоторые объекты имеют значение true. Проще говоря, когда массив объекта повторяется, свойство break объекта становится ложным, даже если оно true. Язык - TypeScript.

предполагается, что вызывается метод getRoute ().

Ниже приведен метод

import { Injectable } from '@angular/core';
import { of, EMPTY, concat } from 'rxjs';
import { HttpService } from '../http.service';
import { take, tap, map, last } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class RouteService {
  activities;
  distanceDB;
  cityFilter = [];
  route: any[];

  constructor(private httpService: HttpService) { }

  setActvities(activities) {
    this.activities = activities;
  }

  getRoute() {
    if (this.activities) {
      return concat(
          this.sortUpActivities(),
          this.calculateBreaks(),
          this.allocateNights()
        ).pipe(
          last()
        );
    }

    return EMPTY;
  }

  /* sort up activities according to city */
  private sortUpActivities() {
    const route = [];
    let counter = 0;

    for (let i = 0; i < this.activities.length; i++) {
      for (let j = 0; j < this.activities[i].length; j++) {
        const city = route.find(r => {
          return r.cityCode == this.activities[i][j].cityCode;
        });

        if (!city) {
          route[counter] = {}
          Object.defineProperty(route[counter], 'break', {
            value: false,
            writable: true
          });

          route[counter].activities = [this.activities[i][j]];
          route[counter].cityCode = this.activities[i][j].cityCode;
          counter++;
        } else {
          city.activities.push(this.activities[i][j]);
        }
      }
    }

    this.route = route;
    return of(this.route);
  }

  /* cacluate breaks required in each city */
  private calculateBreaks() {
    let timeSincePreviousBreak = 7;
    let transitTime = 0;

    return this.httpService.getCityToCity(this.cityFilter).pipe
    (
      take(1),

      tap<any[]>(cityToCity => {
        for (let i = 0; i < this.route.length; i++) {
          let totalActivityTime = 0;;
          for (const ea of this.route[i].activities) {
            totalActivityTime += ea.duration;
          }

          if (this.route[i+1]) {
            const cityToCityInfo =
              cityToCity.find(c => c.from == this.route[i].cityName
                && c.to == this.route[i+1].cityName) ||
              cityToCity.find(c => c.from == this.route[i+1].cityName
                && c.to == this.route[i].cityName);

              if (cityToCityInfo) {
                transitTime = cityToCityInfo.time || 0; // `|| 0` because of DB probable problem
              } else {
                transitTime = 0; // `|| 0` because of probable DB problem
              }
          } else {
            transitTime = 0; // because it is perhapse last city
          }

          const totalTime = timeSincePreviousBreak + totalActivityTime + transitTime;

          this.route[i].activityTime = totalActivityTime;
          if (totalTime >= 9) {
            this.route[i].break = true;
            timeSincePreviousBreak = transitTime;
          } else {
            this.route[i].break = false;
            timeSincePreviousBreak = totalTime;
          }
        }
      }),

      map(cityToCity => { return this.route })
    );
  }


  /* allocate nights according to breaks */
  private allocateNights() {
    for (let i = 0; i < this.route.length; i++) {
      if (this.route[i].break) {
        Object.defineProperty(this.route[i], 'nights', {
          value: 0,
          writable: true
        });

        if (this.route[i].activityTime <= 7) {
          this.route[i].nights = 1;
        } else if (this.route[i].activityTime <= 14) {
          this.route[i].nights = 2;
        } else {
          this.route[i].nights = 3;
        }
      } else {
        console.log(this.route[i].break);
      }
    }

    return of(this.route);
  }
}

Ниже приведен журнал

Angular is running in the development mode. Call enableProdMode() to enable the production mode. core.js:38781
(5) […]
​
0: {…}
​​
activities: Array [ {…} ]
​​
activityTime: 3
​​
break: true
​​
cityCode: "ELL"
​​
<prototype>: Object { … }
​
1: {…}
​​
activities: Array [ {…} ]
​​
activityTime: 5
​​
break: false
​​
cityCode: "NUW"
​​
<prototype>: Object { … }
​
2: {…}
​​
activities: Array [ {…}, {…} ]
​​
activityTime: 10
​​
break: true
​​
cityCode: "KAN"
​​
<prototype>: Object { … }
​
3: {…}
​​
activities: Array [ {…} ]
​​
activityTime: 5
​​
break: false
​​
cityCode: "YAL"
​​
<prototype>: Object { … }
​
4: {…}
​​
activities: Array(3) [ {…}, {…}, {…} ]
​​
activityTime: 12
​​
break: true
​​
cityCode: "GAL"
​​
<prototype>: Object { … }
​
length: 5
​
<prototype>: Array []
route.service.ts:118:12

----------------------------------------------------
false 5 route.service.ts:135:16
----------------------------------------------------
(5) […]
​
0: {…}
​​
activities: Array [ {…} ]
​​
activityTime: 3
​​
break: true
​​
cityCode: "ELL"
​​
<prototype>: Object { … }
​
1: {…}
​​
activities: Array [ {…} ]
​​
activityTime: 5
​​
break: false
​​
cityCode: "NUW"
​​
<prototype>: Object { … }
​
2: {…}
​​
activities: Array [ {…}, {…} ]
​​
activityTime: 10
​​
break: true
​​
cityCode: "KAN"
​​
<prototype>: Object { … }
​
3: {…}
​​
activities: Array [ {…} ]
​​
activityTime: 5
​​
break: false
​​
cityCode: "YAL"
​​
<prototype>: Object { … }
​
4: {…}
​​
activities: Array(3) [ {…}, {…}, {…} ]
​​
activityTime: 12
​​
break: true
​​
cityCode: "GAL"
​​
<prototype>: Object { … }
​
length: 5
​
<prototype>: Array []
route.service.ts:139:12
...