所以基本上我在一個不和諧的機器人中有這個代碼,它會出現在一般聊天中,它說“從 1 到 10 猜出正確的數字”,每次都是一個亂數。
所以,這段代碼應該做的是,每次猜到一個不正確的數字時,它都會更新“數字行”,使數字是什么稍微明顯一點。
示例:他們猜測數字 1、4、5 和 7。
嵌入應該看起來像
1 _ _ 4 5 _ 7 _ _ _,但發生的事情是它不會保存每一個猜測,所以它只會用最后一次猜測的數字更新嵌入
_ _ _ _ _ _ 7 _ _ _ (像這樣),那么我如何存盤所有不正確的猜測答案,按照我想要的方式作業?
代碼:https : //www.toptal.com/developers/hastebin/rowexaketi.js
uj5u.com熱心網友回復:
您可以擁有一個包含所有錯誤猜測的陣列。在您的函式可見的范圍內創建該陣列,然后使用includes方法檢查之前是否嘗試過該數字。
例子:
const triedNumbers = [5,9,10]; // Start it as empty array, this is just for testing
const possibleValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Use reduce instead of mapping to transform the array into a string later
const finalString = possibleValues.reduce((accumulated, current) => {
if(triedNumbers.includes(current)) return `${accumulated}${current}`;
return `${accumulated}_`;
}, '');
console.log(finalString);
鏈接以減少檔案。
幾個建議:更改代碼的變數名稱,您有多個索引:index、index3、index4,這使得閱讀和理解代碼的作業方式變得非常困難。此外,如果您要創建以后不會發生變異的變數,請使用 const 而不是 let。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368955.html
標籤:javascript
上一篇:如何將兩列文本合并為一列?
