首页 > 解决方案 > 有没有办法根据用户输入的时间来调用我的函数

问题描述

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

我试图迭代并将结果推送到一个数组中,但它只推送相同的结果例如 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 次。

标签: javascript

解决方案


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

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"]

这应该完美无瑕地为您工作


推荐阅读