javascript - 无法连接两个变量

标签 javascript arrays string-concatenation

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

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

    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));

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

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

 // 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数组的随机索引组成。下一行将这些索引映射到实际的单词。最后一行将所有这些连接成一个由单个空格分隔的句子,并带有调用者指定的可选句子结尾。

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

为了方便再次链接:http://www.es6fiddle.net/isadgquw/

关于javascript - 无法连接两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39145261/

相关文章:

javascript - Rails 功能测试assert_select javascript respond_to

c# - C 中 char 存储为 int 数组?如何将其转换为 C#

c - 在 C 语言中使用扫描输入变量初始化整数数组

image - 类型错误:无法连接 'str' 和 'pygame.Surface' 对象

javascript - 在 Redux 状态下存储具有原型(prototype)函数的对象

javascript - 使用 JavaScript 从网站获取 JSON

javascript - 关于如何编写 window.resize 函数的一些建议?

c++ - 相对于函数输入初始化全局数组

ruby - 重复一个字符串,副本之间有空格

c++ - 静态初始化顺序和字符串连接