[英]Numbers from inside a string without regex?
我正在和一些朋友一起為游戲聊天室制作一個機器人,但我陷入了僵局。 有沒有一種可靠的方法可以從一串文本中獲取數字,而不會完全破壞沒有經驗的腳本小子的大腦? 這是迄今為止我能想到的最好的,為了說明起見,變量稍微簡化了:
var k = [0];
function dieRoll(m,n) {
for(i = 0; i < m; i++) {
k[i] = Math.floor(Math.random()*n)+1;
}
}
var m = text[5];
var n = text[7];
if (text === 'roll '+m+'d'+n) {
dieRoll(m,n)
console.log(k);
}
最大的問題是它僅限於個位數輸入。
編輯:循環查找整數的文本正是我正在尋找的那種東西。 我沒有太多的編程經驗,所以我可能最終會得到過於復雜和混亂的意大利面條式代碼,這會讓任何遠程專業人士感到尷尬。 至於我正在尋找的輸入格式,“擲[骰子數]d[骰子上的最高數字]”。 對於不知道的人來說,這是大多數桌面角色扮演游戲使用的符號。 例如,對於兩個普通的六面骰子,“擲 2d6”。
編輯:並不是說我一定反對正則表達式,我只是想能夠了解發生了什么,以便當我需要編輯或重用代碼時,我可以這樣做而不會完全發瘋。
編輯:非常感謝大家! split() 似乎正是我要找的! 這可能需要一些試驗和錯誤,但我想我可以讓她在這個周末按照她應該的方式工作(是的,我稱我的機器人為“她”)。
基本上,您需要查看您使用的輸入的格式,並確定有關它的某些事實。 以下是我根據您的問題做出的假設。
1) "roll" 命令首先出現,后跟一個空格,並且 2) 在該命令之后,您將獲得x d y形式的骰子信息。
鑒於這些限制,這里有一些應該起作用的東西:
function getRollParameters(inputCommand) { var inputWords = inputCommand.split(' '); //Split our input around the space, into an array containing the text before and after the space as two separate elements. var diceInfo = inputWords[1]; //Store the second element as "diceInfo" var diceDetails = diceInfo.split('d'); //Split this diceInfo into two sections, that before and after the "d" - ie, the number of dice, and the sides. //assign each part of the dicedetails to an appropriate variable var dice = diceDetails[0]; var sides = diceDetails[1]; //return our two pieces of information as a convenient object. return { "dice": dice, "sides": sides }; } //a couple of demonstrations console.log(getRollParameters("roll 5d8")); console.log(getRollParameters("roll 126d2"));
實際上,我們首先將字符串拆分為“命令”和“參數”——我們想要的信息。 然后,我們使用“d”作為中點來拆分我們的論點。 這給了我們兩個數字——一個在 d 之前,一個在 d 之后。 然后我們將這些值分配給變量,並且可以隨心所欲地使用它們。
這顯然不會處理更具創意或靈活的輸入,並且不會超出所示示例進行測試,但它應該是一個不錯的起點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.