所以我正在用 html5/javascript 编写一个在线 mad lib 应用程序,截至目前我个人删除了我希望用户替换的单词,并注入了它们的值。我想让程序循环遍历一个字符串(故事),并用他们输入的单词替换我在数组中每种情况下选择的单词。例如,如果我希望 Noun1 是单词“hill”并且他们为 Noun1 输入的单词是“ferret”,那么每次故事会说“hill”时,它将被替换为“ferret”。使用字符串和数组是最好的做法还是有更好的方法?你介意告诉我如何在java-script中循环字符串以及如何替换值吗?
这是我目前拥有的。
function makeML(){
//get variables from form
var firstNoun = window.document.myForm.txtfirstNoun.value;
var secondNoun = document.myForm.txtsecondNoun.value;
var firstVerb = document.myForm.txtfirstVerb.value;
var thirdNoun = document.myForm.txtthirdNoun.value;
var fourthNoun = document.myForm.txtfourthNoun.value;
var secondVerb = document.myForm.txtsecondVerb.value;
var firstBody = document.myForm.txtfirstBody.value;
var story = "";
story = "Hansel and Gretel sat by the " ;
story += firstNoun;
story += ". and when noon came, each ate a little piece of ";
story += secondNoun;
story += ", and as they heard the ";
story += firstVerb;
story += " of the wood-axe, they believed that their father was near. It was not the axe; however, but a ";
story += thirdNoun;
story += " which he had fastened to a ";
story += fourthNoun;
story += " which the wind was blowing backwards and forwards. And as they had been ";
story += secondVerb;
story += " such a long time, their ";
story += firstBody;
story += " closed with fatigue, and they fell fast asleep."
story += "!\" \nThe End.... or is it."
document.myForm.txtStory.value = story;
我还有一点,但没有必要展示,除非你们出于任何原因需要它来更新。