這是我當前的代碼:
const diceRoll = Math.trunc(Math.random() * 6) 1;
const diceRollArr = Array.from ({length: 4}, (_, i) => diceRoll[i]);
console.log(diceRollArr); //Returns: (4)[undefined, undefined, undefined, undefined]
無法理解我所缺少的東西。如果我做:
const diceRoll = Math.trunc(Math.random() * 6) 1;
const diceRollArr = Array.from ({length: 4}, (_, i) => diceRoll);
它將為給定的陣列長度生成相同的擲骰子,因此我需要一種方法來為每個索引位置進行擲骰子。任何幫助將不勝感激,謝謝!
uj5u.com熱心網友回復:
嘗試轉換diceRoll
為函式,并將其用于映射 Array 的元素:
const diceRoll = _ => Math.trunc(Math.random() * 6) 1;
const diceRollArr = [...Array(4)].map(diceRoll);
console.log(`[${diceRollArr}]`);
uj5u.com熱心網友回復:
diceRoll
當它是變數時,您將作為陣列訪問。您還需要diceRoll
成為一個函式并在每次迭代時呼叫它
const diceRoll = () => Math.trunc(Math.random() * 6) 1;
const diceRollArr = Array.from ({length: 4}, diceRoll);
console.log(diceRollArr);
uj5u.com熱心網友回復:
您可以使用我最喜歡[...Array(x)].map(() => ...)
的回圈 x 次,然后在回圈內生成一個亂數Math.random
const numberOfRolls = 10
const rolls = [...Array(numberOfRolls)].map(() => (~~(Math.random() * 6) 1))
console.log(rolls)
uj5u.com熱心網友回復:
我最近做了一個擲骰子課程。出于某種原因,我懷疑你是桌面角色扮演游戲玩家,所以這有點適合你。
只需創建一個新的 DicePool 類,并通過呼叫該roll()
方法生成新的擲骰子。
function randomize(max, min = 1) {
return Math.floor(Math.random() * max) min;
}
class DicePool {
constructor(combinationStr) {
let [amount, type, modification] = this.#breakdown(combinationStr);
this.amount = amount;
this.type = type;
this.modification = modification;
}
roll() {
let result = 0;
for (var i = 0; i < this.amount; i ) {
result = randomize(this.type);
}
result = this.modification;
return result;
}
#breakdown(combinationStr) {
let [diceStr, modification] = this.#stripModification(combinationStr);
let [amount, type] = diceStr.split('d');
return [amount, type, modification];
}
#stripModification(str) {
if (str.indexOf('-') != -1) {
let aritmic = 1;
let breakArr = str.split('-');
breakArr[aritmic] *= -1
return breakArr;
} else if (str.indexOf(' ') != -1) {
return str.split(' ');
}
return [str, 0];
}
}
const d6 = new DicePool('1d6');
const diceRollArr = Array.from ({length: 4}, () => d6.roll());
console.log(diceRollArr)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505615.html
標籤:javascript 数组 功能 索引 骰子
上一篇:為什么useState設定在useEffect中不起作用?我該如何解決這個問題?
下一篇:按鈕未在React.js中呈現