-2

我正在尝试使用 javascript 构建一个随机字母数字生成器,它将随机生成车辆登记号,因此字符串必须采用特定格式:三个大写字母、三个数字、两个大写字母。前三个字母和数字可以是完全随机的,即 ABC123 或 GDS342。最后两个字母是特定省/州的缩写,即 MP、ZN、GP 等。例如:GDS342GP。当在网页上单击按钮时,注册号应显示在文本区域中。

关于如何做到这一点的任何建议?

先感谢您。

4

1 回答 1

1

String.fromCharCode()如果您输入 65 到 90 之间的数字,会给您一个大写字母。因此,如果您使用此函数 3 次,其中 3 个随机数字介于(包括)65-90 之间,您可以生成三个随机大写字母:

const getRandomLetters = function(count) {
  let acc = ''; // the resulting string (to return once results appended)
  for(let i = 0; i < count; i++) { // generate amount
    const randomCharCode = Math.floor(Math.random() * (91 - 65)) + 65;
    acc += String.fromCharCode(randomCharCode);
  }
  return acc;
}

const characters = getRandomLetters(3);
console.log(characters);

要生成三个随机数,您可以以相同的方式执行此操作。为此,您可以使用Math.floor(Math.random() * 10)生成一个从 0 到 9 的随机整数。有更简单的方法可以做到这一点,但是这种方法将允许您获得诸如000050不在数百个但仍被视为三个数字的数字:

const getRandomNumbers = function(count) {
  let acc = '';
  for(let i = 0; i < count; i++) {
    acc += ~~(Math.random() * 10); // Note: ~~ is the same as Math.floor (just a little faster)
  }
  return acc;
}

const numbers = getRandomNumbers(3);
console.log(numbers);

由于您尚未指定如何选择状态,因此我将为您提供一种随机选择它们的方法。

您可以将所有状态存储在一个数组中:

const states = ['MP', 'ZN', 'GP'];

然后选择一个介于(包括)零到状态数组长度减 1 之间的随机数,以从该数组中获取随机索引。然后,这将允许您通过使用此数字作为索引来访问随机状态:

const states = ['MP', 'ZN', 'GP'];
const randomIndex = ~~(Math.random() * states.length); // random int from: [0, 3) -> gives ints: 0, 1, 2

const state = states[randomIndex];
console.log(state);

现在你可以结合所有这些想法来生成你的随机字符串。您还可以向元素添加一个onclick方法,该方法将在按下时调用一个函数。<button>此外,您还可以添加一个id<textarea>以便您的 javascript 访问它并将其更改value为生成的字符串:

const getRandomLetters = function(count) {
  let acc = ''; // the resulting string (to return once results appended)
  for(let i = 0; i < count; i++) { // generate amount
    let randomCharCode = Math.floor(Math.random() * (91 - 65)) + 65;
    acc += String.fromCharCode(randomCharCode);
  }
  return acc;
}




const getRandomNumbers = function(count) {
  let acc = '';
  for(let i = 0; i < count; i++) {
    acc += ~~(Math.random() * 10); // Note: ~~ is the same as Math.floor (just a little faster)
  }
  return acc;
}

const generatePlate = function() {
  const states = ['MP', 'ZN', 'GP'];
  const randomIndex = ~~(Math.random() * states.length); // random int from: [0, 3) -> gives ints: 0, 1, 2
  
  const characters = getRandomLetters(3);
  const numbers = getRandomNumbers(3);
  const state = states[randomIndex];
  
  const resultPlate = characters + numbers  + state;
  document.getElementById('output').value = resultPlate;
}
<button onclick="generatePlate()">Generate</button>
<br />
<textarea id="output"></textarea>

于 2018-12-26T11:55:11.377 回答