首页 > 解决方案 > 使用 JavaScript Mad Libs 挑战进行 DRY 编程

问题描述

我是编程新手。

我知道我可以使用函数和循环来避免重复此代码,但我需要帮助。任何人?

var questions = 3;    
var questionsCount = ' [' + questions + ' questions left]';    
var adjective = prompt('Please type an adjective' + questionsCount);   
questions -= 1;   
questionsCount = ' [' + questions + ' questions left]';
var verb = prompt('Please type a verb' + questionsCount);
questions -= 1;
questionsCount = ' [' + questions + ' questions left]';
var noun = prompt('Please type a noun' + questionsCount);
alert('All done. Ready for the message?');
var sentence = "There once was a " + adjective;
sentence += ' programmer who wanted to use JavaScript to ' + verb;
sentence += ' the ' + noun + '.';
document.write(sentence);

标签: javascript

解决方案


我会使用一个字符串模板,其中包含例如{{noun}}要替换为名词,它使用正则表达式来提示用户进行替换:

const template = 'There once was a {{adjective}} programmer who wanted to use JavaScript to {{verb}} the {{noun}}.';
let questions = 3;
const result = template.replace(
  /{{(.*?)}}/g,
  (_, typeOfSpeechNeeded) => prompt(`Please type a ${typeOfSpeechNeeded}, ${questions--} question(s) left`)
);

console.log(result);

正则表达式

{{(.*?)}}

匹配{{,后跟一些字符,然后是}},这些字符被放入捕获组 - 这允许.replace检查捕获组以确定typeOfSpeechNeeded在提示中显示的内容。

/g则表达式中的 使其成为全局的,它替换所有匹配项,而不仅仅是第一个匹配项。

反引号字符串只是插入字符串的一种更易读的方式:

prompt(`Please type a ${typeOfSpeechNeeded}, ${questions--} question(s) left`)

相当于

prompt('Please type a ' + typeOfSpeechNeeded + ', ' + questions-- + ' question(s) left')

推荐阅读