确定字符串中的所有字母是否都按字母顺序排列 [英] Determine if all letters in a string are in alphabetical order JavaScript

查看:345
本文介绍了确定字符串中的所有字母是否都按字母顺序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写JavaScript函数来确定字符串中的所有字母是否都按字母顺序排列.以下内容将继续返回"SyntaxError:意外的令牌默认值"

I'm attempting to write a JavaScript function to determine if all letters in a string are in alphabetical order. The following would keep returning "SyntaxError: Unexpected token default"

function orderedWords(str) {
    var s=str.toLowerCase().split("");
    for(var i=0; i<s.length; i++) {
        var default = s[i];
        if (s[i+1] >= default)
            default = s[i+1];
        else return false;
    }
    return true;
}

orderedWords("aaabcdefffz"); // true
orderedWords("abcdefzjjab"); // false

非常感谢您的帮助.

推荐答案

default是JavaScript中的关键字,不能为变量名.

default is a keyword in JavaScript, and cannot be a variable name.

另外,您还有一个逻辑问题:如果您迭代到length,则在最后一次迭代中,您将根据undefined检查最后一个字符;测试将失败,您将return false.重写为:

Also, you have a logic issue: if you iterate up to length, in your last iteration you will check the last character against undefined; the test will fail, and you will return false. Rewrite into:

for(var i=0; i<s.length - 1; i++) {

实际上,我什至不知道为什么要使用该变量,因为它与其余代码无关.这也应该工作(另外,为了方便计算,我将范围从[0..length-1)移到了[1..length)):

I am not actually even sure why you're using that variable, since it has no bearing to the rest of your code. This should work as well (also, I moved the range from [0..length-1) to [1..length) for easier calculation):

function orderedWords(str) {
    var s=str.toLowerCase().split("");
    for(var i=1; i<s.length; i++) {
        if (s[i - 1] > s[i]) {
            return false;
        }
    }
    return true;
}

更简单,更简短:

function orderedWords(str) {
    return str == str.split('').sort().join('');
}

这篇关于确定字符串中的所有字母是否都按字母顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆