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));
添加回答
舉報