一个函数可以用于多种用途吗? (多功能)

时间:2018-09-18 08:52:54

标签: javascript jquery

因此,让您大致了解我在做什么:我在其中创建了一个带有数组的函数,然后将该数组(因此该函数)分配给输入字段的占位符(也是一个单独的函数)。但是,我有第三个函数(也包含一个输入字段),并且这个函数也应该有一个随机占位符文本。我的问题:是否可以使用保存数组的函数来创建另一个数组,然后将该数组用于其他函数?这些是我正在谈论的功能:

function placeholderRandomizer() {
    let arrRandomizer = ['Fill out the time you ran!', 'Hey! fill out the time you ran!', 'What was the time you ran this time?!'];
    let randomizer = Math.floor(Math.random() * arrRandomizer.length);
    let valueRandomizer = arrRandomizer[randomizer];

    return valueRandomizer;
}

function getInputTime() {
    let inputField = ($('<input/>', {
        'type': 'text',
        'name': 'time',
        'placeholder': placeholderRandomizer(),
        'class': 'form form-control'
    }));
    return inputField;
}

我想同时使用placeholderRandomizer的功能(但是具有不同的数组等),因此基本上一个功能应该将2个不同的输入字段随机化(所以2个不同的功能)。

function getInputDistance() {
    let inputField = ($('<input/>', {
        'type': 'text',
        'name': 'distance',
        'placeholder':'tt',
        'class': 'form form-control'
    }));
    return inputField;
}

编辑:我的意思是,我想要一个带有新句子和一个新功能的全新数组,但我想为其他功能创建一个新功能似乎非常不切实际,因此要弄清楚这个问题:是否可以在一个函数中创建多个随机数并将这些数组随机数分配给不同的函数。

2 个答案:

答案 0 :(得分:0)

您只需要两个功能即可。然后,您两次调用getInput即可获得所需的内容。

function pickRandomItem(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

function getInput(elementName, placeholderArr) {
    return ($('<input/>', {
        'type': 'text',
        'name': elementName,
        'placeholder': pickRandomItem(placeholderArr),
        'class': 'form form-control'
    }));
}

let inputTimeElement = getInput('time', ([
    'Fill out the time you ran!', 
    'Hey! fill out the time you ran!', 
    'What was the time you ran this time?!'
]); 

let inputDistanceElement = getInput('distance', ([
    'Fill out the distance you ran!', 
    'Hey! fill out the distance you ran!', 
    'What was the distance you ran this time?!'
]);

答案 1 :(得分:0)

使用一个数组和模板文字:

function pickRandomItem(name) {
  let arr = [`Fill out the ${name} you ran!`,
    `Hey! fill out the ${name} you ran!`,
    `What was the ${name} you ran this time?!`
  ]
  return arr[Math.floor(Math.random() * arr.length)];
}

function getInput(elementName) {
  return $('<input/>', {
    'type': 'text',
    'name': elementName,
    'placeholder': pickRandomItem(elementName),
    'class': 'form form-control'
  });
}
let inputTimeElement = getInput('time')
let inputDistanceElement = getInput('distance')
$("body").append(inputTimeElement)
  .append("<br/>")
  .append(inputDistanceElement);
input {
  width: 250px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>