代码之家  ›  专栏  ›  技术社区  ›  Dream_Cap

为什么数组中的原始项会被Object.assign?

  •  0
  • Dream_Cap  · 技术社区  · 6 年前

    我有一个单元测试,它产生了一些我没想到的东西:

    背景:我正在用角度/测试驱动开发制作一个简单的todo列表。

    问题:当我对数组中的项调用editTask时,它会更改该项的值。但是,我看不到它在原始数组中是如何变化的,因为在我测试的方法中从未访问过原始数组。请帮助我连接如何更改原始阵列?看来对象.assign为什么要这么做?

     describe('editTask', () => {
        it('should update the task by id', () => {
          const dummyTask1 = { id: 1, name: 'test', status: false };
          service.tasks.push(dummyTask1); //refers to TestBed.get(TaskService)
          const id = 1;
          const values = { name: 'cat', status: false };
    
          service.editTask(id, values);
          console.log(service.tasks); // why does this log this object? [Object{id: 1, name: 'cat', status: false}]
          expect(service.tasks[0].name).toEqual(values.name); // Test passes
        });
      });
    

      editTask(id, values) {
        const task = this.getTask(id);
    
        if (!task) {
          return;
        }
    
        Object.assign(task, values); //How does this line change the array?
    
        return task;
      }
    
      getTask(id: number) {
        return this.tasks.filter(task => task.id === id).pop(); //is this altering the original array somehow?
      }
    

    export class TaskService {
      tasks: any = [];
      lastId = 0;
    
      constructor() { }
    
      addTask(task) {
        if (!task.id) {
          task.id = this.lastId + 1;
        }
    
        this.tasks.push(task);
      }
    
      editTask(id, values) {
        const task = this.getTask(id);
    
        if (!task) {
          return;
        }
    
        Object.assign(task, values);
    
        return task;
      }
    
      deleteTask(id: number) {
        this.tasks = this.tasks.filter(task => task.id !== id);
      }
    
      toggleStatus(task) {
        const updatedTask = this.editTask(task.id, { status: !task.status});
    
        return updatedTask;
      }
    
      getTasks() {
        return of(this.tasks);
      }
    
      getTask(id: number) {
        return this.tasks.filter(task => task.id === id).pop();
      }
    }
    

    以下是github回购协议: https://github.com/capozzic1/todo-tdd

    1 回复  |  直到 6 年前
        1
  •  1
  •   RedJandal    6 年前

    这个 getTask() 方法是使用数组获取对数组中的项的引用 filter() 方法。

    然后使用 Object.assign()

    所以现在,项的内存中引用的值发生了变化。因为它是内存中的一个引用,所以您将看到原始项被更改。

    推荐文章