检查字母顺序
我是一个新手,正在努力掌握 javascript。请帮助我巩固我的基础。
输入将是一串字母。
以下是要求。
如果满足以下条件,函数应返回 true:
字母按字母顺序排列。 (不区分大小写)
仅传递一个字母作为输入。示例:
isAlphabet('abc') === true isAlphabet ('aBc') === true isAlphabet ('a') === true isAlphabet ('mnoprqst') === false isAlphabet ('') === false isAlphabet ('tt') === false
function isAlphabet(letters) {
const string = letters.toLowerCase();
for (let i = 0; i < string.length; i++) {
const diff = string.charCodeAt(i + 1) - string.charCodeAt(i);
if (diff === 1) {
continue;
} else if (string === '') {
return false;
} else if (string.length === 1) {
return true;
} else {
return false;
}
}
return true;
}
I am a newbie who is trying hard to have a grip on javascript. please help me to consolidate my fundamentals.
input will be a string of letters.
following are the requirements.
function should return true if following conditions satisfy:
letters are in alphabetical order. (case insensitive)
only one letter is passed as input. example :
isAlphabet ('abc') === true isAlphabet ('aBc') === true isAlphabet ('a') === true isAlphabet ('mnoprqst') === false isAlphabet ('') === false isAlphabet ('tt') === false
function isAlphabet(letters) {
const string = letters.toLowerCase();
for (let i = 0; i < string.length; i++) {
const diff = string.charCodeAt(i + 1) - string.charCodeAt(i);
if (diff === 1) {
continue;
} else if (string === '') {
return false;
} else if (string.length === 1) {
return true;
} else {
return false;
}
}
return true;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,更好的做法是从处理边缘情况开始你的函数,而不是把它们放在中间的某个地方。这样,函数就会尽快返回 - 并且它比
if..else
语句的瀑布更容易阅读。It's generally a better practice to start your function off with dealing with the edge-cases rather than putting them somewhere in the middle. That way, the function returns as soon as it can - and it's a lot easier to read than a waterfall of
if..else
statements.您的想法是正确的,但它可以简化为在特定错误条件下失败,即当较小的字符跟随较大的字符时:
You've got the right idea, but it can be simplified to just fail on a particular error condition, i.e when a smaller character follows a larger one:
您可以使用简单的方法来实现与下面相同的效果
注意:标记答案可以解决您的问题。
You can use the simple way to achieve the same as below
Note: Mark the answer is resolves your problem.