【发布时间】:2020-03-17 20:33:59
【问题描述】:
我正在尝试编写从对象加载文本并随机分配性别的东西以一种持续存在的方式
const output = {
text: "He thought that his sweater would suit him"
}
我希望能够让对象在展示时随机显示“他认为他的毛衣会适合他”或“她认为她的毛衣会适合她”。为了解决这个问题,而不必创建两个不同的对象——一个用于男性,一个用于女性——我已经做到了这一点:
const gender = {
male: {
pronoun: "he",
possPronoun: "his",
possAdjective: "his",
object: "him",
moniker: "sir"
},
female: {
pronoun: "she",
possPronoun: "hers",
possAdjective: "her",
object: "her",
moniker: "ma'am"
}
};
function randGender (usage) { // Add lettercase functionality later
return Math.floor(Math.random()*2) == 1 ? gender.female[usage] : gender.male[usage]
}
console.log(randGender("pronoun"));
我卡住的地方是之后该怎么办。
const output = {
text: `${randGender("pronoun")} thought that ${randGender("possAdjective")} sweater would suit ${randGender("object")}`
}
console.log(output.text); //she thought that his sweater would suit her
...当我希望它只保留一种性别时显然不起作用。
我认为有一些解决方法,例如使用 output.text.male 和 output.text.female 并在调用对象时执行随机部分。有什么方法可以按照我的方式进行吗?
感谢您的帮助!
【问题讨论】:
标签: javascript object dynamic literals