有没有一种方法可以根据用户输入的时间来调用我的函数

时间:2019-04-21 17:17:15

标签: javascript

我正在为报价生成器编写程序,我需要一些帮助,以使报价生成生成器的次数取决于用户输入的内容。

我尝试将结果迭代并将其推入数组,但它只会将相同的结果推送4次

//Flowers quotes
'use strict';

const randomFlowersQuote = () => {

    const fragBeginning = ['These are very beautiful ', 'I like looking at ', ' Today We saw some new ', 'There a nice '];
    const fragMiddle = ['flower pots', 'hibiscuss trees', 'red roses', 'lily flowers', 'rare flowers'];

    const fragEnd = [' i would love to buy one', ' they are very nice', ' they are so breathtaking', ' in the shop'];

    //Random generated quotes

    const fragBeginningRandom = [Math.floor(Math.random() * fragBeginning.length)];
    const fragMiddelRandom = [Math.floor(Math.random() * fragMiddle.length)];
    const fragEndRandom = [Math.floor(Math.random() * fragBeginning.length)];
    const fullQuote = [fragBeginning[fragBeginningRandom] + fragMiddle[fragMiddelRandom] + fragEnd[fragEndRandom]];

    return fullQuote;
}

console.log(randomFlowersQuote());

我希望用户输入3时,它将调用该函数3次。

1 个答案:

答案 0 :(得分:1)

好的,我有一个解决方案, 我修改了您的代码并尝试运行此代码,这为您提供了所需的输出。据我说:)

const fragBeginning = ['These are very beautiful ', 'I like looking at ', ' Today We saw some new ', 'There a nice '];
const fragMiddle = ['flower pots', 'hibiscuss trees', 'red roses', 'lily flowers', 'rare flowers'];

const fragEnd = [' i would love to buy one', ' they are very nice', ' they are so breathtaking', ' in the shop'];





    function RandomGeneratedQuotes(number)
    {   
       var quotes = [];
       for(var i = 0; i < number; i++){
            const fragBeginningRandom = [Math.floor(Math.random() * fragBeginning.length)];
            const fragMiddelRandom = [Math.floor(Math.random() * fragMiddle.length)];
            const fragEndRandom = [Math.floor(Math.random() * fragBeginning.length)];
            const fullQuote = [fragBeginning[fragBeginningRandom] + fragMiddle[fragMiddelRandom] + fragEnd[fragEndRandom]];
            quotes.push(fullQuote);
        } return quotes;
    }    

函数调用输出将为:

console.log(RandomGeneratedQuotes(3))
VM431:1 
(3) [Array(1), Array(1), Array(1)]
0: [" Today We saw some new rare flowers i would love to buy one"]
1: ["These are very beautiful flower pots i would love to buy one"]
2: [" Today We saw some new rare flowers in the shop"]

这应该对您无懈可击