如何在随机句子生成器中避免switch语句代码重复?
问题
我正在开发一个随机句子生成器,生成的句子会从对象的属性(nouns、tenses、adjectives、conjunctions)中随机选取内容,句子结构固定为「名词 时态 形容词 连词 名词 时态 形容词」,示例输出为"Birds will be wild and robots will be free"。目前我用for-in循环+switch语句实现,但存在大量代码重复,想找更高效的实现方式。
原实现代码:
// Generating a random number function generateRandomNumber(num) { return Math.floor(Math.random() * num) } // The object containing the properties and values, the values will be the words in the sentence. const sentenceElements = { nouns: [ 'animals', 'elephants', 'mice', 'monkeys', 'lions', 'zebras', 'people', 'buildings', 'trees', 'flowers', 'bugs', 'cats', 'birds', 'mushrooms', 'computers', 'robots', 'dinosaurs' ], tenses: [ 'were', 'are', 'will be', ], adjectives: [ 'best', 'bad', 'better', 'huge', 'busy', 'free', 'great', 'hard', 'loud', 'old', 'right', 'special', 'weird', 'brave', 'wild', 'adorable', 'smart', 'crazy', 'cute', 'funny' ], conjunctions: [ 'because', 'however', 'since', 'but', 'whereas', 'and', 'also', 'as', 'when' ] } // Empty array for the selected words to be pushed into let newArray = [] // Looping through the properties in the object to push each randomly selected value into the empty array. for(let i in sentenceElements) { let randArrayIndex = generateRandomNumber(sentenceElements[i].length) switch(i) { case 'nouns': newArray.push(`${sentenceElements[i][randArrayIndex]}`) break case 'tenses': newArray.push(`${sentenceElements[i][randArrayIndex]}`) break case 'adjectives': newArray.push(`${sentenceElements[i][randArrayIndex]}`) break case 'conjunctions': newArray.push(`${sentenceElements[i][randArrayIndex]}`) break } } // Used another for in loop to add more words to the array using the same object. for(let i in sentenceElements) { let randArrayIndex = generateRandomNumber(sentenceElements[i].length) switch(i) { case 'nouns': newArray.push(`${sentenceElements[i][randArrayIndex]}`) break case 'tenses': newArray.push(`${sentenceElements[i][randArrayIndex]}`) break case 'adjectives': newArray.push(`${sentenceElements[i][randArrayIndex]}`) break } } // Adding the values from newArray to a string called completeSentence while capitalizing the first letter function completeSentence(sentence) { const formatting = newArray.join(' ') const formatted = formatting[0].toUpperCase() + formatting.substring(1) console.log(formatted) } completeSentence(newArray);
优化方案
你的核心问题是没有利用固定的句子结构直接生成内容,反而通过遍历整个对象导致冗余代码。可以从以下几点优化:
- 提取通用随机选择函数:把从数组中随机选元素的逻辑封装成独立函数,避免重复计算随机索引。
- 按句子结构直接拼接:既然句子结构固定,直接按「名词 时态 形容词 连词 名词 时态 形容词」的顺序调用随机选择函数,不需要遍历整个对象。
- 简化格式化逻辑:格式化函数不依赖外部数组,仅接收参数处理,降低耦合度。
优化后的代码:
// 从数组中随机选取一个元素 function getRandomElement(arr) { const randomIndex = Math.floor(Math.random() * arr.length); return arr[randomIndex]; } const sentenceElements = { nouns: ['animals', 'elephants', 'mice', 'monkeys', 'lions', 'zebras', 'people', 'buildings', 'trees', 'flowers', 'bugs', 'cats', 'birds', 'mushrooms', 'computers', 'robots', 'dinosaurs'], tenses: ['were', 'are', 'will be'], adjectives: ['best', 'bad', 'better', 'huge', 'busy', 'free', 'great', 'hard', 'loud', 'old', 'right', 'special', 'weird', 'brave', 'wild', 'adorable', 'smart', 'crazy', 'cute', 'funny'], conjunctions: ['because', 'however', 'since', 'but', 'whereas', 'and', 'also', 'as', 'when'] }; // 按照固定结构生成句子单词列表 function generateSentenceWords() { return [ getRandomElement(sentenceElements.nouns), getRandomElement(sentenceElements.tenses), getRandomElement(sentenceElements.adjectives), getRandomElement(sentenceElements.conjunctions), getRandomElement(sentenceElements.nouns), getRandomElement(sentenceElements.tenses), getRandomElement(sentenceElements.adjectives) ]; } // 格式化句子:首字母大写并拼接成字符串 function formatSentence(words) { const sentence = words.join(' '); return sentence.charAt(0).toUpperCase() + sentence.slice(1); } // 生成并输出句子 const sentenceWords = generateSentenceWords(); const formattedSentence = formatSentence(sentenceWords); console.log(formattedSentence);
优化说明
- 去除冗余代码:删掉了原代码中两次重复的for-in循环和switch语句,直接按固定结构按需获取元素,代码量大幅减少。
- 函数职责单一:每个函数只负责一件事——
getRandomElement处理随机选元素逻辑,generateSentenceWords组装单词列表,formatSentence处理格式化,代码更清晰易维护。 - 降低耦合度:原格式化函数依赖外部的
newArray,优化后函数仅通过参数接收数据,避免了不必要的外部依赖。
内容的提问来源于stack exchange,提问作者aFinalFan
相关产品推荐
相关产品推荐

