javascript - 使用 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);
解决方案
我会使用一个字符串模板,其中包含例如{{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')
推荐阅读
- static - 重新加载静态页面时未调用 Next.js getInitialProps() 方法
- python - 如何从区间中选择值并确定最大值?
- react-native - 单击屏幕时是否有另一种关闭键盘的方法
- ios - 如何在swift ios中使用访问令牌登录LinkedIn
- vue.js - Vuejs x5-gmaps地图标记不显示
- sql - 以显示属于不同作者的书籍的方式进行查询
- kotlin - 为什么这个 Kotlin 程序中没有运行 setter 函数
- python - 如何使用 Python Selenium Firefox webdriver 将网页转换为 PDF?
- javascript - 根据 Piotnet 表单上的选定选项更改图像(Wordpress 插件)
- entity-framework - 使用实体框架将整个类持久化为 JSON