簡體   English   中英

在Java中引用變量的正確方法

[英]Proper Way to Reference Variables in Javascript

我目前正在重構代碼,並且想將一個名為REFERENCE_LIST的對象數組導出到另一個文件。

reference.js

export const REFERENCE_LIST = [
 {name:"TypeA", foodList:foodAList}, 
 {name:"TypeB", foodList:foodBList}
]

export const foodAList = ['apple', 'orange', 'banana']
];

export const foodBList = ['meat', 'fish']
];

但是, REFERENCE_LISTfoodList字段始終為“未定義”。 我是否錯誤地引用了這些數組?

您不能在JS中引用變量。 盡管您可以引用對象值-但需要為此首先創建那些對象:

export const foodAList = ['apple', 'orange', 'banana'];
export const foodBList = ['meat', 'fish'];

export const REFERENCE_LIST = [
  {name:"TypeA", foodList:foodAList}, 
  {name:"TypeB", foodList:foodBList}
];

您還可以在創建順序無關緊要的地方使用吸氣劑:

export const REFERENCE_LIST = [
  {name:"TypeA", get foodList() { return foodAList; }}, 
  {name:"TypeB", get foodList() { return foodBList; }}
];

但是,即使在初始化常量之前對它們進行評估時,即使是那些也會引發異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM