2016-09-05 2 views
1

Я создал скрипт для генерации случайных предложений из слов и фраз в массиве. Это работает.петля функция случайное число раз в javascript

Я хочу сделать абзац из этих случайных предложений. То, что я сделал, повторяет одно и то же предложение, вместо того, чтобы снова и снова запускать функцию для создания новых предложений.

Я думаю, моя ошибка находится в этой части кода.

const randParagraph = (len, end, words, wordLen) => 
[...Array(len)].map(() => addCommaAfter(fullSentWithEnd,sentLength(5,12))) 
.join(' ') + (end || ' '); 

fullSentWithEnd является окончательной функцией при создании предложений.

const fullSentWithEnd = randSentence(ipsumText, sentLength(5,12), '.') 

и addAfterComma разделяет предложение на добавление запятой.

const addCommaAfter = (sentence, index) => { 
word_split = sentence.split(" "); 
word_split[index] = word_split[index]+","; 
word_split[0] = word_split[0][0].toUpperCase() + word_split[0].slice(1); 
return word_split.join(" "); 

}

Я думал, что в randParagraph новый массив говорил запустить addCommaAfter и передать в fullSentWithEnd, и сказать ему, чтобы запустить случайное число раз от 5 до 12. Но теперь мне интересно, если это на самом деле говорит это, или если это то, что говорит ему повторить тот же результат.

Хотелось бы подумать.

const ipsumText = ["adventure", "endless youth", "dust", "iconic landmark", "spontaneous", "carefree", "selvedge","on the road", "open road", "stay true", "free spirit", "urban", "live on the edge", "the true wanderer", "vintage motorcyle", "american lifestyle", "epic landscape", "low slung denim", "naturaL"]; 
 

 
const randInt = (lower, upper) => 
 
Math.floor(Math.random() * (upper-lower)) + lower 
 

 
const randWord = (words) => words[randInt(0, words.length)] 
 

 
const randSentence = (words, len, end) => 
 
[...Array(len)].map(() => randWord(words)).join(' ') + (end || ' ') 
 

 
const randWordWithEnd = (end) => randWord(ipsumText) + end 
 
const randWordWithFullStop = randWordWithEnd('. ') 
 
const randWordWithComma = randWordWithEnd(', ') 
 

 
const sentLength = (min,max) => {return Math.floor(Math.random() * (max - min + 1)) + min;}; 
 

 
const fullSentWithEnd = randSentence(ipsumText, sentLength(5,12), '.') 
 
const fullSentNoEnd = randSentence(ipsumText, sentLength(5,12)) 
 
const fullSentComposed = fullSentNoEnd + randWordWithFullStop 
 

 
const addCommaAfter = (sentence, index) => { 
 
\t word_split = sentence.split(" "); 
 
\t word_split[index] = word_split[index]+","; 
 
\t word_split[0] = word_split[0][0].toUpperCase() + word_split[0].slice(1); 
 
\t return word_split.join(" "); 
 
} 
 

 
console.log(fullSentWithEnd) 
 
console.log(" "); 
 
console.log(addCommaAfter(fullSentWithEnd,sentLength(3,8))); 
 

 
const randParagraph = (len, end, words, wordLen) => 
 
[...Array(len)].map(() => addCommaAfter(fullSentWithEnd,sentLength(5,12))) 
 
.join(' ') + (end || ' '); 
 

 
console.log(randParagraph(sentLength(5,8), '', ipsumText, sentLength(5,12)));

+0

вы можете дать код, который может быть запущен? –

+0

просто добавил фрагмент выше @SufianSaory – garrethwills

ответ

0

вы посеяли addCommaAfter c от randParagraph func с таким же предложением. вместо этого измените сеяние на случайные предложения, как показано ниже, он создаст абзац со случайными предложениями.

const randParagraph = (len, end, words, wordLen) => 
    [...Array(len)].map(() => addCommaAfter(randSentence(words, sentLength(5, 12), '.'), sentLength(5, 12))) 
     .join(' ') + (end || ' '); 

Полный код:

const ipsumText = ["adventure", "endless youth", "dust", "iconic landmark", "spontaneous", "carefree", "selvedge", "on the road", "open road", "stay true", "free spirit", "urban", "live on the edge", "the true wanderer", "vintage motorcyle", "american lifestyle", "epic landscape", "low slung denim", "naturaL"]; 
 

 
const randInt = (lower, upper) => 
 
    Math.floor(Math.random() * (upper - lower)) + lower 
 

 
const randWord = (words) => words[randInt(0, words.length)] 
 

 
const randSentence = (words, len, end) => 
 
    [...Array(len)].map(() => randWord(words)).join(' ') + (end || ' ') 
 

 
const randWordWithEnd = (end) => randWord(ipsumText) + end 
 
const randWordWithFullStop = randWordWithEnd('. ') 
 
const randWordWithComma = randWordWithEnd(', ') 
 

 
const sentLength = (min, max) => { return Math.floor(Math.random() * (max - min + 1)) + min; }; 
 

 
const fullSentWithEnd = randSentence(ipsumText, sentLength(5, 12), '.') 
 
const fullSentNoEnd = randSentence(ipsumText, sentLength(5, 12)) 
 
const fullSentComposed = fullSentNoEnd + randWordWithFullStop 
 

 
const addCommaAfter = (sentence, index) => { 
 
    word_split = sentence.split(" "); 
 
    if (index >= word_split.length) { 
 
     index = word_split.length - 1; 
 
    } 
 
    word_split[index] = word_split[index] + ","; 
 
    word_split[0] = word_split[0][0].toUpperCase() + word_split[0].slice(1); 
 
    return word_split.join(" "); 
 
} 
 

 
console.log(fullSentWithEnd) 
 
console.log(" "); 
 
console.log(addCommaAfter(fullSentWithEnd, sentLength(3, 8))); 
 

 
const randParagraph = (len, end, words, wordLen) => 
 
    [...Array(len)].map(() => addCommaAfter(randSentence(words, sentLength(5, 12), '.'), sentLength(5, 12))) 
 
     .join(' ') + (end || ' '); 
 

 
console.log(randParagraph(sentLength(5, 8), '', ipsumText, sentLength(5, 12)));

+0

вправо, я вижу, что теперь @sufian. Благодарю. Там появилось несколько «неопределенных». Это было бы просто потому, что параметр ничего не передал. – garrethwills

+0

Да, из-за проблемы с индексом в addCommaAfter функция undefined наступает. теперь исправлено. @ garrethwills –

+0

Я могу видеть, что вы добавили оператор if, так что если случайное целое число, определяющее длину раскола, было длиннее предложения, оно становится на единицу меньше длины предложения. Большой, – garrethwills

1

Я не понимаю, что именно делает ваш код, но я получил эту маленькую основу для генерации случайных текстов:

ucfirst = s => s[0].toUpperCase() + s.slice(1); 
 

 
rand = (min, max) => min + Math.floor(Math.random() * (max - min)); 
 

 
sample = a => a[rand(0, a.length)]; 
 

 
times = (n, fn) => [...Array(n)].map(fn); 
 

 
seq = (min, max, fn, sep) => times(rand(min, max), fn).join(sep); 
 

 
// this will use random "words" 
 

 
char =() => sample("abcdefghjiklmnopqrstuwvxyz"); 
 
word = seq(1, 10, char, ''); 
 

 
// this will use an array of predefined words 
 

 
words = [ 
 
    'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'I', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 
 
    'at', 'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one', 'all', 
 
    'would', 'there', 'their', 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when', 'make', 
 
    'can', 'like', 'time', 'no', 'just', 'him', 'know', 'take', 'person', 'into', 'year', 'your', 'good', 'some', 'could', 
 
    'them', 'see', 'other', 'than', 'then', 'now', 'look', 'only', 'come', 'its', 'over', 'think', 'also', 'back', 'after', 
 
    'use', 'two', 'how', 'our', 'work', 'first', 'well', 'way', 'even', 'new', 'want', 'because', 'any', 'these', 'give', 
 
    'day', 'most', 'us']; 
 

 
word =() => sample(words) 
 

 
phrase =() => seq(3, 10, word, ' '); 
 

 
sent =() => seq(1, 10, phrase, ', '); 
 

 
sentence =() => ucfirst(sent()) + sample('.?!'); 
 

 
paragraph =() => seq(1, 10, sentence, ' '); 
 

 
text =() => seq(2, 20, paragraph, '\n\n'); 
 

 
console.log(text())

+0

мой код создает предложения из ассортимента фраз и слов, которые я сохранил в массиве. Идея состоит в том, чтобы генерировать текст ipsum, который имеет вкус или подходит для темы. Ваш код создает свои собственные слова из того, что я вижу, используя буквы алфавита случайным образом. Моя проблема заключается в том, что мне не удалось получить предложения в случайном порядке через абзац. Они повторяют. – garrethwills

+0

Просто замените слово «word» в приведенном выше коде своей собственной реализацией (например, «sample (array of of words)». – georg

+0

sorry @georg Я не следую. Я все еще новичок в этом. Я не уверен как вы предлагаете я добавляю его.Я попытался изменить его для моего массива, но, очевидно, не понял его правильно – garrethwills

Смежные вопросы