无法连接两个变量

Can't get two variables to concatenate

我是新手,做一个小练习来练习数组。我已经尝试从以前的文章中解决这个问题,但 none 似乎有相关的场景。

我想使用数组中的短语将句子随机生成段落。我的随机句子生成部分工作正常。

    var 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"];

//a simple function to print a sentence //

var sentence = function (y) { 
var printSentence = "";
for (i=0; i<7; i++) { 
    //random selection of string from array //
    var x = Math.floor(Math.random() * 20);
    printSentence += y [x] + " "; 
}
return printSentence
};

console.log(sentence(ipsumText));

但现在我希望能够在句子末尾添加一个逗号或句号。

因为句子中使用的数组中的每个 word/phrase 后面都打印了 space,所以我需要在它后面添加一个带有句号或逗号的额外单词以避免 space他们之间。为此,我创建了一个额外的变量

 // create a word and full stop to end a sentence//
var addFullstop = ipsumText[Math.floor(Math.random() * ipsumText.length)] + ". ";
var addComma = ipsumText[Math.floor(Math.random() * ipsumText.length)] + ", ";

这些变量按照我的预期自行工作。他们打印一个带有逗号或句号的随机单词。

但是现在我不知道如何让它们添加到句子的末尾。我已经尝试了很多引用此处文章的版本,但我遗漏了一些东西,因为当我测试它时,我没有在控制台日志中打印任何内容。

这是我最近尝试过的。

// add the sentence and new ending together //
var fullSentence = sentence(ipsumText) + addFullstop;
console.log(fullSentence)

有人可以解释为什么这行不通吗?并建议尝试解决方案? 谢谢

参见 ES6 fiddle:http://www.es6fiddle.net/isadgquw/

您的示例有效。但是考虑一种更灵活的不同方法。你给它单词的数组,你想要句子多长,如果你想要句子的结尾,就传入end,否则,直接不传就不用了。

第一行生成一个长度为 count 的数组,它由随机索引组成,用于索引 words 数组。下一行将这些索引映射到实际单词。最后一行将所有这些连接成一个句子,由一个 space 分隔,句子的结尾可选,由调用者指定。

const randomSent = (words, count, end) =>
    [...Array(count)].map(() => Math.floor(Math.random() * words.length))
                     .map(i => words[i])
                     .join(' ') + (end || '')

randomSent (['one','two','x','compound word','etc'], 10, '! ')
// x x one x compound word one x etc two two!

为了更加灵活,可以考虑为每个任务制作一个函数。代码是可重用的、特定的,并且没有使用可变变量,因此可以轻松地测试、理解和编写您喜欢的代码:

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(', ')

// Now, test it!
const fullSentWithEnd = randSentence(ipsumText, 8, '!!')
const fullSentNoEnd = randSentence(ipsumText, 5)
const fullSentComposed = fullSentNoEnd + randWordWithFullStop

Link 再次为方便起见:http://www.es6fiddle.net/isadgquw/