而循环帮助word生成器

时间:2015-08-17 23:39:41

标签: javascript while-loop

我已经开始了,并且我尝试制作一个代码,为它生成单词,放置字母,遵循一套规则。我希望它将所有字母放入一个数组中,然后加入数组来制作一个单词。问题是,我无法让它改变数组。有人可以看一下代码来弄清楚出了什么问题吗?这是一个JSFiddle(抱歉,如果我的代码很乱)。

https://jsfiddle.net/rxgab975/

var words = [];
var consonants = ["B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "P", "R", "S", "T", "V", "Z"];
var consonantPairsBeg = ["SP","ST","SK","SL","SM","FP","FT","FK","FL","FM","CP","CT","CK","CL","CM","KL","KR","GL","GR","VL","JT","JL","JK"];
var consonantPairsEnd = ["RS","RP","RT","RK","RL","RM","RG","RV","PS","TS","KS","LS","MS","GS","VS","LP","LT","LK","LM","LG","LV","PC","TC","KC","LC","MC","GC","VC"];
var vowels = ["A", "E", "I", "O", "U", "AA", "AI", "AO", "II"];
var order = "(B)V(E)(C)F";
var wordcount = 1000;

function pickLet(type) {
var chance = Math.random();
if (type === "B") {
    if (chance >= 0.5) {
        return consonantPairsBeg[Math.floor((Math.random() * consonantPairsBeg.length))];
    } else {
        return consonants[Math.floor((Math.random() * consonants.length))];
    }
} else if (type === "V") {
    return vowels[Math.floor((Math.random() * vowels.length))];
} else if (type === "E") {
            if (chance >= 0.5) {
        return consonantPairsEnd[Math.floor((Math.random() * consonantPairsEnd.length))];
    } else {
        return consonants[Math.floor((Math.random() * consonants.length))];
    }
} else if (type === "C") {
    return consonants[Math.floor((Math.random() * consonants.length))];
}
};
function genWord() {
var sylFin = false;
var wordPos = 0;
var partCount = 0;
var chance = 0;
var prob = Math.random();
var parts = [];
while (wordFin = false) {
    if (order[wordPos] === "(") {
        chance = Math.random();
        wordPos++;
    } else if (order[wordPos] === ")") {
        chance = 0;
        wordPos++;
    } else if(order[wordPos] === "B") {
        if (prob > chance) {
            parts[partCount] = pickLet("B");
            partCount++;
        }
        wordPos++;
    } else if(order[wordPos] === "V") {
        if (prob > chance) {
            parts[partCount] = pickLet("V");
            partCount++;
        }
        wordPos++;
    } else if(order[wordPos] === "E") {
        if (prob > chance) {
            parts[partCount] = pickLet("E");
            partCount++;
        }
        wordPos++;
    } else if(order[wordPos] === "C") {
        if (prob > chance) {
            parts[partCount] = pickLet("C");
            partCount++;
        }
        wordPos++;
    } else if(order[wordPos] === "F") {
        sylFin = true;
    }
}
return parts;
};

1 个答案:

答案 0 :(得分:0)

出乎意料:    1-更正genWord()中的条件语句如下:

 While (wordFin == false) {

2-建议在使用之前使用var关键字声明wordFin。    3-我没有看到你停止循环的机制,你在逻辑中使用wordcount来停止循环?

希望这有点帮助。