带有循环javascript

时间:2019-01-11 10:18:39

标签: javascript

我正在使用带循环的报价生成器。生成器必须从数组1 +数组2 +数组3返回随机报价(例如'love''将是''您的任务'),但是当它获得“和平”“将是”“您的开始”时,它必须发出警报: “你发现我了”。 我认为的问题是函数select.quote无法正常工作

let array1 = [ " peace " , "love" , " money"];
let array2 = [ " will be " , "will never be ", "maybe will be"];
let array3 = [" your end", " your start", "your tasks"];

function finalQuote(...arrs) {
let quote = '';
for (let i = 0; i <arrs.length; i++) {
quote += arrs[i][Math.floor(Math.random() * 3)];{
return quote;}

select.quote = function(){
if (arrays){
if (array1 === 'peace', array2 === 'will be', array3 === 'your end'){
alert("you found me!");
}}else{
let FinalQuote =finalQuote(array1, array2, array3);}}

qt_btn.addEventListener("click", function(event) {
finalQuote();});

1 个答案:

答案 0 :(得分:2)

可以做很多事情来整理代码,但是下面的方法应该可以解决很多问题。

let array1 = [ "peace " , "love" , "money"];
let array2 = [ "will be " , "will never be ", "maybe will be"];
let array3 = ["your end", "your start", "your tasks"];

function checkStringForMatch (str, word) {
    return str.indexOf(word) !== -1
}

function finalQuote(...arrs) {
let quote = '';
    for (let i = 0; i < arrs.length; i++) {
        quote += arrs[i][Math.floor(Math.random() * 3)] + ' ';
    }
    if (checkStringForMatch(quote, 'peace') && checkStringForMatch(quote, 'will be') && checkStringForMatch(quote, 'your end')){
        alert("you found me!");
    } else {
        alert(quote)
    }
}

qt_btn.addEventListener("click", function(event) {
    finalQuote(array1, array2, array3);
});