gpt4 book ai didi

javascript - 设置对对象属性的引用

转载 作者:行者123 更新时间:2023-11-28 06:45:58 25 4
gpt4 key购买 nike

我有一个对象数组,我想设置和重置对其中一个对象的属性的引用。假设我有以下内容:

var TheReference = null;
var TheArrayOfObjects = [];
var TheObject = {};

TheObject.SomeProp1 = "test1";
TheObject.SomeProp2 = "test2";

TheArrayOfObjects.push(TheObject); // this array could contain hundreds of objects

TheReference = TheObject.SomeProp1; // here I know it's not a reference.
TheReference = "update"; // so of course it doesn't update the object's property

我的目标是存储对对象属性的引用,然后通过访问该引用来更新该属性。如果我有 TheReference = TheObject 那么这将允许我到达该特定对象,但我希望访问该对象的属性,以便我可以编写 TheReference = "update" 并且该值在对象的属性中更新。有什么方法可以存储对对象属性的引用?

最佳答案

只有当对象属性本身是“真实”对象时,您才能存储对该属性的引用。上面的代码将无法按照您的要求工作,因为您正在尝试引用字符串,但这将:

var TheReference = null;
var TheArrayOfObjects = [];
var TheObject = {};

TheObject.SomeProp1 = {p1: "test1", p2: "test2"};
TheObject.SomeProp2 = {p3: "test3", p4: "test4"};

TheArrayOfObjects.push(TheObject); // this array could contain hundreds of objects

TheReference = TheObject.SomeProp1; // here I know it's not a reference.
alert(TheReference.p1); // will show 'test1'

关于javascript - 设置对对象属性的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33418136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com