2 回答

TA贡献1856条经验 获得超5个赞
您需要为性别而不是某些道具返回整个内部对象,并且基于此您可以检索对象内部的道具:
function getRandGender() {
return Math.floor(Math.random() * 2) == 1 ? gender.female : gender.male
}
const randGender = getRandGender();
const output = {
text: `${randGender.pronoun} thought that ${randGender.possAdjective} sweater would suit ${randGender.object}`
}

TA贡献1825条经验 获得超6个赞
那是因为您在分配output.text值时调用了函数 randGender 三个不同的时间,所以它在每次调用时随机生成一个性别。
最好使用“随机化器”将变量定义为对象一次,然后在分配output.text.
请参阅下面的片段。
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"
}
};
const randomGender = Math.floor(Math.random() * 2) == 1 ?
gender.female :
gender.male;
console.log(`Random Gender:`, randomGender);
const output = {
text: `${randomGender.pronoun} thought that ${randomGender.possAdjective} sweater would suit ${randomGender.object}`
}
document.write(JSON.stringify(output));
添加回答
举报