【发布时间】:2020-01-29 22:29:42
【问题描述】:
我必须创建一个程序来获取提示符的第一个字母,如果该字母介于 a 和 k 之间,那么它必须产生特定的输出,如果它介于 l 和 p 之间,则以此类推。有没有办法在不写下每个字母的情况下做到这一点? (对不起,我是新程序员)
【问题讨论】:
-
你试过什么?您可以使用基本的比较(关系)运算符
标签: javascript alphabetical letter
我必须创建一个程序来获取提示符的第一个字母,如果该字母介于 a 和 k 之间,那么它必须产生特定的输出,如果它介于 l 和 p 之间,则以此类推。有没有办法在不写下每个字母的情况下做到这一点? (对不起,我是新程序员)
【问题讨论】:
标签: javascript alphabetical letter
我认为您应该先尝试解决问题,然后再询问 - 这样您就可以展示您已经尝试过的内容。
我认为下面的 sn-p 为您指明了正确的方向 - 但它需要任何字符,而不仅仅是字母。您需要过滤掉所有不是小写字母的内容。
// 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>
【讨论】: