考慮以下 :
let data = {
"world": "bc",
"d": "ef",
"g": "hi",
};
let panel = {
"hello": {
"world": {},
}
};
let dataTree = panel.hello;
let exampleBool = true;
if (exampleBool) {
dataTree = panel.hello.world;
}
Object.assign(dataTree, data);
dataTree.world = "xz";
console.log(dataTree.world);
console.log(data.world);
console.log(data === dataTree);
輸出 :
xz
bc
false
所需的輸出:
xz
xz
true
我想為由 參考的物件屬性設定一個值,該值dataTree可以根據exampleBool. 我想鏈接由databe參考的物件dataTree,換句話說,使dataTree === data是true。
問題Object.assign在于它復制了每個屬性data,在我的情況下,data鍵可以是數千個長度,所以我不想克隆每個屬性。
有什么辦法可以在 JS 中做到這一點?
uj5u.com熱心網友回復:
您可以分配dataTree給data:
let data = {
"world": "bc",
"d": "ef",
"g": "hi",
};
let panel = {
"hello": {
"world": {},
}
};
let dataTree = panel.hello;
let exampleBool = true;
if (exampleBool) {
dataTree = panel.hello.world;
}
data = dataTree;
dataTree.world = "xz";
console.log(dataTree.world);
console.log(data.world);
console.log(data === dataTree);
uj5u.com熱心網友回復:
我想為參考的物件屬性設定一個值
dataTree
該變數dataTree不是對物件屬性的參考。JS 中沒有這樣的東西。dataTree確實參考了{ "world": {} }物件(或者,在條件賦值之后,{}物件),就是這樣。您不能改變通過變數獲取物件的屬性。
相反,存盤基礎物件和屬性名稱:
let data = {
"world": "bc",
"d": "ef",
"g": "hi",
};
let panel = {
"hello": {
"world": {},
}
};
let dataTreeBase = panel,
dataTreeProp = "hello";
let exampleBool = true;
if (exampleBool) {
dataTreeBase = panel.hello;
dataTreeProp = "world";
}
dataTreeBase[dataTreeProp] = data;
dataTreeBase[dataTreeProp].world = "xz";
console.log(dataTreeBase[dataTreeProp].world);
console.log(data.world);
console.log(data === dataTreeBase[dataTreeProp]);
當然,有多種方法可以使用 getter/setter 或方法在函式或物件中抽象 this,但您無法僅使用普通變數來實作這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345968.html
標籤:javascript
上一篇:如何撰寫一個javascript函式來來回切換按鈕顏色?
下一篇:Vue.js3和搜索
