[英]Why does accessing an object literal with bracket notation and a key containing spaces result in undefined?
[英]How to not set a key in object literal notation if the value of the key is undefined
我正在使用Redux創建一個RPG角色生成器。 在我的減速器中,我希望能夠修改齒輪並跟蹤這些修改。 修改可以具有等級,但不一定必須具有等級。
因此,如果等級未定義,我寧願不記錄下來。 那么,如果值未定義,有沒有辦法不以對象文字表示法添加鍵?
gearName將是要修改的齒輪的字符串。
mod是一個包含有關mod的屬性的對象,例如+ rating耐火等級或其他。
等級是代表修改值的數字。
const purchaseGear = (state, action) => {
const { gearName, mod, rating } = action.parameter;
switch (action.type) {
case MOD_GEAR:
return {
...state,
[gearName]: {
...state[gearName],
mods: {
...state[gearName].mods,
[mod.name]: {
...mod,
rating
}
},
cost: mod.cost * (rating || 1)
}
}
}
2ality.com上的Axel Rauschmayer提出了以下模式:
const cond = false;
const obj = {
...(cond ? {a: 1} : {}),
b: 2,
};
// {b: 2}
所以在你的情況下
...(rating !== undefined ? {rating: rating} : {})
請記住,只有當引擎已經支持Object rest / spread-proposal時 ,此模式才有效。 它可以在Chrome v58中使用,但我尚未在其他平台上進行過測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.