当我将一个对象链接到一个对象数组时,两个对象的值是如何链接的

How are the value of two objects linked when I link an object to an array of objects?

本文关键字:链接 一个对象 两个 对象 何链接 数组      更新时间:2023-09-26

我有一个tes测试服务,在我的 Typescript 代码中显示了两个对象:

test: ITestView;
tests: ITestView[];

此代码检查 tes.tests 数组中的每个对象,当id匹配时,它将数组中的一个对象分配给等于另一个对象tes.test

tes.tests.forEach((test: ITestRow) => {
    test.current = false;
    if (test.id == id) {
        tes.test = test; // << Linking them somehow here
        test.current = true;
    }
});

稍后我这样做:

tes.test.current = false;

此代码将 tes.tests[0].current 的值设置为 false,将 tes.test.current 的值设置为 false。

当我现在这样做时:

tes.test = null;

此代码将 tes.test 的值设置为 null,但不对 tes.tests[] 数组执行任何操作。

有人可以解释为什么它不会影响tes.tests[]数组吗?

test = foo; // test references existing object foo
tests[0] = test; // test[0] also references existing object foo
test = null; // test doesn't reference anything, but tests[0] still does

根据您的期望,您可以执行以下操作:

tests[0] = null; // tests[0] doesn't reference anything

或:

tests.splice(0,1); // removed the 1st item from the tests
// not tests array became shorter!

我认为快速简单的答案是

tes.test = null;

不会破坏它指向的对象。 tes.test现在什么也没指出。

澄清一下,tes.test.current = false更改这两个对象是因为它引用了tes.test指向的对象的current键。

tes.test = null;

上面的代码没有对 tes.tests[] 进行任何更改,因为它很简单tes.test指向任何内容,而不是更改它指向的对象。我希望我清楚!