亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript中性別的動態對象值

Javascript中性別的動態對象值

守候你守候我 2022-01-07 16:21:12
我正在嘗試編寫一些從對象加載文本并以持續存在的方式隨機分配性別的東西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 并在調用對象時執行隨機部分。有什么方法可以按照我的方式進行嗎?
查看完整描述

2 回答

?
RISEBY

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}`

}


查看完整回答
反對 回復 2022-01-07
?
胡子哥哥

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));


查看完整回答
反對 回復 2022-01-07
  • 2 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號