Javascript 摩卡,阵列阵列和范围阵列

Javascript 摩卡,阵列阵列和范围阵列,javascript,arrays,mocha.js,Javascript,Arrays,Mocha.js,我有一个类似于此的代码: let Foo = class Foo { constructor(a) { this.a = a.slice(); } bar() { this.set(0, 1, [1]); this.set(1, 1, [1]); } set(x, y, n) { this.a[x][y] = n; } get() { return thi

我有一个类似于此的代码:

let Foo = class Foo {
    constructor(a) {
        this.a = a.slice();
    }

    bar() {
        this.set(0, 1, [1]);
        this.set(1, 1, [1]);
    }

    set(x, y, n) {
        this.a[x][y] = n;
    }

    get() {
        return this.a;
    }
};

module.exports = Foo;
因此,属性whis是数组的数组、修改它的
set
函数、使用
set
的函数和getter

现在我用mocha编写单元测试:

const Foo = require('./../foo.js'),
    source = [[1, 2, 3], [4, 5, 6]],
    chai = require('chai'),
    expect = chai.expect;

describe('Foo', () => {
    describe('bar', () => {
        it('expect to modify the array', () => {
            let foo = new Foo(source);

            foo.bar();

            expect(foo.a).to.deep.equal([[1, [1], 3], [4, [1], 6]]);
        });
    });

    describe('get', () => {
        it('expect to return the array', () => {
            let foo = new Foo(source);
            expect(foo.get()).to.deep.equal([1, 2, 3]);
        });
    });
});
在其中,我在开始时声明了
source
变量,并使用它在每个测试中构建一个新的
Foo

然而,结果是。。。
bar
测试修改
get
测试中
foo
的属性:

  Foo
    bar
      ✓ expect to modify the array
    get
      1) expect to return the array


  1 passing (19ms)
  1 failing

  1) Foo get expect to return the array:

      AssertionError: expected [ [ 1, [ 1 ], 3 ], [ 4, [ 1 ], 6 ] ] to deeply equal [ 1, 2, 3 ]
      + expected - actual

       [
      -  [
      -    1
      -    [
      -      1
      -    ]
      -    3
      -  ]
      -  [
      -    4
      -    [
      -      1
      -    ]
      -    6
      -  ]
      +  1
      +  2
      +  3
       ]

      at Proxy.assertEqual (node_modules/chai/lib/chai/core/assertions.js:1020:19)
      at Proxy.methodWrapper (node_modules/chai/lib/chai/utils/addMethod.js:57:25)
      at Context.it (test/foo.js:20:30)
在mocha测试中使用匿名函数而不是箭头函数不会改变任何东西,使用或不使用
splice
也可以通过值复制源


我错过什么了吗?很明显,我以某种方式将同一引用归因于同一数组中的两个
foo
的属性,但我不知道如何,更重要的是,如何确保我可以创建单独的
foo
s。

这是因为
this.a=a.slice()
只需要一个浅拷贝。但是由于
a
是嵌套数组,因此在
this.a
source
中都可以看到嵌套数组中的任何更改

你可以改变:

this.a = a.slice();
致:

请注意,您的第二个测试可能需要以任何方式进行更改,因为您没有将其与
source
初始化为的内容进行比较。因此,改变:

expect(foo.get()).to.deep.equal([1, 2, 3]);
致:


@Jonasw在真实的代码中,会进行检查以确保它不会失败:)尝试使用一个简单的
a.map((b)=>{return b.slice()}
,但它不起作用,并且认为我走错了方向,应该住得更深。是的,移动应用程序没有发送绿色标记:)
expect(foo.get()).to.deep.equal([1, 2, 3]);
expect(foo.get()).to.deep.equal([[1, 2, 3], [4, 5, 6]]);