假設我想創建一個鍵為 USD 和 non-USD 的物件。如下:
let obj = {
USD: {
sourceValue: 100
destinationValue: 10
},
non-USD: {
sourceValue: 10
destinationValue: 100
}
}
除了這里,我應該能夠傳遞任何貨幣,而不是非美元,比如新元或港幣,我應該得到非美元貨幣的結果。
所以,如果我寫了obj[currency].sourceValue,currency=HKD那么我應該得到10
我不想使用obj[1].sourceValue貨幣價值是動態的。
另外,我不想使用if(currency!='USD') index=1然后obj[index].sourceValue
所以,我的問題是,在定義物件時我應該在 non-USD 的地方寫什么?我檢查了計算名稱,但我不確定,如何將長貨幣陣列作為鍵名傳遞并從中過濾美元?
uj5u.com熱心網友回復:
您實際上需要使用 if else like 條件。像這樣說
const key = currency == "USD" ? "USD" : "non-USD";
// and then get the data like this
obj[currency].sourceValue
uj5u.com熱心網友回復:
我不知道 js/ts 中有一個選項會具有鍵查找語法(如obj[currency])并執行您想要的行為,同時保持物件obj“普通”。
obj但是有些選項可以通過對和/或不同的呼叫語法進行一些修改來完成您想要的操作。(我能想到的唯一方法是保持obj完全不受影響,然后需要對貨幣進行一些更改。)
選項 1:添加 get 函式呼叫
const obj1 = {
get: function(currency) {
return this[currency === "USD" ? "USD" : "non-USD"]
},
USD: {
sourceValue: 100,
destinationValue: 10
},
"non-USD": {
sourceValue: 10,
destinationValue: 100
}
}
或者,如果您無法更改物件的來源,請使用Object.assign. 在這里,您可以決定是否要改變原始物件 ( Object.assign(target, ...)) 或創建一個新物件Object.assign({}, target, ...)
const addGetter = (target) => Object.assign({}, target, {
get: (currency) => target[currency === "USD" ? "USD" : "non-USD"]
})
const obj1 = addGetter(obj) // <-- pass in the original obj
用法: obj1.get(currency).sourceValue
選項 2:使用代理
代理檔案,支持
提供您想要的鍵查找語法,但是 imo,這種方法有點容易出錯,因為除“USD”之外的任何訪問(按鍵或屬性索引)都將回傳“非 USD”值。console.log(obj)物件也被包裝,在某些控制臺中記錄 () 時隱藏物件詳細資訊。
const useProxy = (obj) => new Proxy(obj, {
get: (target, currency) => target[currency === "USD" ? "USD" : "non-USD"]
})
const obj2 = useProxy(obj) // <-- pass in the original obj
用法: obj2[currency].sourceValue
演示
檢查代碼注釋和控制臺輸出
const addGetter = (target) => Object.assign({}, target, {
get: (currency) => target[currency === "USD" ? "USD" : "non-USD"]
})
const useProxy = (obj) => new Proxy(obj, {
get: (target, currency) => target[currency === "USD" ? "USD" : "non-USD"]
})
const obj = {
USD: {
sourceValue: 100,
destinationValue: 10
},
"non-USD": {
sourceValue: 10,
destinationValue: 100
}
}
// Option 1
const obj1 = addGetter(obj)
// Option 2
const obj2 = useProxy(obj)
const c = ["USD", "EUR", "HKD", "non-USD"]
console.log("obj1.get(currency).sourceValue", c.map(currency => currency " -> " obj1.get(currency).sourceValue))
console.log("obj2[currency].sourceValue", c.map(currency => currency " -> " obj2[currency].sourceValue))
// Option 2 feels a bit error-prone, as any other access will return the fallback value for "non-USD"
console.log("obj2.length", c.map(currency => obj2.length))
console.log("obj2.randomProp", c.map(currency => obj2.randomProp))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/423075.html
標籤:
下一篇:使用PHPMailer庫發送附件
