Determine if all letters in a string are in alphabetical order JavaScript

耗尽温柔 提交于 2020-02-07 12:01:07

问题


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

Any help is much appreciated.


回答1:


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

EDIT: 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++) {

EDIT2: 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;
}

EDIT3: Simpler, shorter:

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



回答2:


It looks like you're looking for more than a sort? With this function you can use any letter order defined in map, and also the function removes punctuation just in case you need to check messy strings.

var map = "abcdefghijklmnopqrstuvwxyz";

function orderedWords(str,map){
    str = str.replace(/(.)(?=.*\1)/g, "");
    str = str.replace(/\W/g, '');
    var test = ""
    for(var i in map){
        if(str.indexOf(map[i])>-1){
            test += map[i];
        }
    }
    if(test.toLowerCase() == str.toLowerCase()){
        return true;
    }
    return false;
}

console.log(orderedWords("aaabcdefffz", map));
console.log(orderedWords("abcdefzjjab", map));


来源:https://stackoverflow.com/questions/28620703/determine-if-all-letters-in-a-string-are-in-alphabetical-order-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!