【发布时间】:2019-02-24 19:45:05
【问题描述】:
我正在创建一个 lorem ipsum 应用程序,我想单击一个按钮以从随机字符生成随机引号。并且字符之间不会混合引号。但是,每次我单击提交时,它只会显示我在数组中列出的第一个字符的随机引号。我该如何解决这个问题?
const aQuotes = require("./public/quotes/a");
const bQuotes = require("./public/quotes/b");
const cQuotes = require("./public/quotes/c");
const loremIpsum = new GenerateNewText();
function GenerateNewText(){}
GenerateNewText.prototype.getRandomSentence = function() {
const charQuotes =
[
aQuotes,
bQuotes,
cQuotes,
]
for(var i = 0; i < charQuotes.length; i++){
let randomSentence = charQuotes[i][Math.floor(Math.random() * charQuotes[i][Math.floor(Math.random())].length)]
return randomSentence;
}
}
当我运行上面的示例时,它将显示存储在aQuotes 中的随机引用列表,其中包含“未定义”一词。如果我将bQuotes 移动到数组的顶部,那么它将仅显示随机的bQuotes,同时带有“未定义”一词。为什么它只显示数组中第一个元素的结果,为什么显示“未定义”(即aQuotes)?
const aQuotes = [
"Lalalalalalalala.",
"Blah blah blah blah.",
"Blank Blank Blank Blank Blank."
]
module.exports = aQuotes;
我尝试做 charQuotes[i][Math.floor(Math.random())].length * charQuotes[i][Math.floor(Math.random())].length 认为它会首先随机化 charQuotes 数组,然后随机化单个 a/b/cQuotes 数组,但它最终返回了一个数字 169 的块。我尝试过的其他“修复”结果在所有undefined 文本的段落中,所有NaN 的段落中,或显示所有字符的所有引号,并在此处和此处插入单词“未定义”。
如何在每次点击时随机化 charQuotes 数组和我的 a/b/cQuotes 数组中的内容?并摆脱出现的奇怪的“未定义”文本?
我正在使用 Node 和 Express。
【问题讨论】:
-
“但是,每次我点击提交时,它只会显示我在数组中列出的第一个字符的随机引号。” 当
i为0时,值为从return randomSentence;的函数返回 -
好的,我明白你的意思并设置它而不是
for(var i; i < charQuotes.length; i++){ let randomSentence = charQuotes[Math.floor(Math.random() * charQuotes[Math.floor(Math.random())].length)] return randomSentence; },但我只是得到未定义的块。
标签: javascript arrays random