我正在创建一个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
中的随机列表,其中包含“undefined”一词。如果我将bQuotes
移动到数组的顶部,那么它将仅显示随机的bQuotes
,也会显示单词“undefined”。为什么它只显示数组中第一个元素的结果,为什么显示“未定义”(即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
,或显示所有字符的所有引号,其中包含“undefined”一词插入到此处和那里。
如何每次点击随机化charQuotes数组和我的a/b/cQuotes
数组中的内容?并摆脱出现的奇怪的“未定义”文本?
我正在使用Node和Express。
你可以.map()
charQuotes
并从每个输入数组返回一个伪随机值,并进一步.sort()
得到的数组伪随机
const getRandomSentence = () => {
const charQuotes =
[
["a", "b", "c"],
[1, 2, 3],
[1.5, 2.5, 3.5],
];
const r = charQuotes.map(arr => arr[Math.floor(Math.random() * arr.length)])
.sort(_ => 0.5 - Math.random());
return r.join(" ")
}
console.log(getRandomSentence());
你不需要for
循环。您正在输入循环以仅在第一次迭代中返回。这就是为什么你总是得到第一个引号数组。
GenerateNewText.prototype.getRandomSentence = function() {
const allQuotes =
[
aQuotes,
bQuotes,
cQuotes,
]
const characterQuotes = allQuotes[ Math.floor(Math.random() * allQuotes.length) ]
return characterQuotes[ Math.floor(Math.random() * characterQuotes.length) ]
}
如果要从同一个字符生成引号,则需要将字符信息保存在函数作用域外的变量中,或者保存在对象实例中,如下例所示:
GenerateNewText.prototype.allQuotes = [
aQuotes,
bQuotes,
cQuotes,
]
GenerateNewText.prototype.getRandomSentence = function() {
if ( !this.characterQuotes ) {
this.characterQuotes = this.allQuotes[ Math.floor(Math.random() * allQuotes.length) ]
}
return this.characterQuotes[ Math.floor(Math.random() * characterQuotes.length) ]
}