Javascript中字母的过滤范围

问题描述 投票:-4回答:1

我必须创建一个使用提示的第一个字母的程序,如果该字母在a和k之间,那么它必须产生一定的输出,如果它在l和p之间,等等。有没有一种方法可以不将每个字母都写下来? (对不起,我是新编码员)

javascript alphabetical letter
1个回答
0
投票

我认为您应该在提出问题之前先尝试解决问题-这样您就可以展示您已经尝试过的内容。

我认为下面的代码段会为您指明正确的方向-但是它可以使用任何字符,而不仅仅是字母。您需要过滤掉所有不是小写字母的内容。

// UI elements
const input = document.getElementById('input1')
const result = document.getElementById('result')

// input event
// only the first character is taken into account
input.addEventListener('input', function(e) {
  // adding the characters of the input value to an array, and
  // picking the 0th element (or '', if there's no 0th element)
  const a = [...this.value][0] || ''
  let ret = ''

  if (a !== '') {
    // lowercaseing letters, so it's easier to categorize them
    ret = categorizeAlphabet(a.toLowerCase().charCodeAt(0))
  } else {
    ret = 'The input is empty'
  }

  // displaying the result
  result.textContent = ret
})

// you could use this function to filter and categorize
// according to the problem ahead of you - and return the result
// to be displayed.
// In this example this function is rather simple, but
// you can build a more complex return value.
const categorizeAlphabet = (chCode) => {
  return `This is the character code: ${chCode}`
}
<label>
  First character counts:
  <input type="text" id='input1'>
  </label>
<h3 id="result">The input is empty</h3>
© www.soinside.com 2019 - 2024. All rights reserved.