输入的单词是按字母顺序排列的吗?

Is the input word in alphabetical order?

我正在编写一个函数,它将 return truefalse 判断输入字符串是否按字母顺序排列。我得到 undefined 但不确定我缺少什么

function is_alphabetic(str) {
  let result = true;
  for (let count = 1, other_count = 2; count >= str.length - 1, other_count >= str.length; count++,
    other_count++) {
    if (str.at[count] > str.at[other_count]) {
      let result = false
    }
    return result
  }
}
console.log(is_alphabetic('abc'));

这应该可以做到。我使用了 .localeCompare(),因为这会忽略 small/capital 差异,并且还会合理地处理特定于语言的字符,例如德语变音符号。

function is_alphabetic(str){
  return !str.split('').some((v,i,a)=>i&&v.localeCompare(a[i-1])<0)
}
['abcdefg','aacccRt','ashhe','xyz','aüv'].forEach(s=> console.log(s,is_alphabetic(s)) );

我认为如果使用此函数比较字符串会更容易:

var sortAlphabets = function(text) {
    return text.split('').sort().join('');
};

这会产生如下结果:

sortAlphabets("abghi")
output: "abghi"

或者:

sortAlphabets("ibvjpqjk")
output: "bijjkpqv"

如果您想知道您的字符串是否按字母顺序排序,您可以使用:

var myString = "abcezxy"
sortAlphabets(myString) == myString
output: false

或者以防万一,您想创建一个特定的函数:

function isSorted(myString) {
    return sortAlphabets(myString) == myString
}

对于这种情况,您可以使用:

isSorted("abc")

var sortAlphabets = function(text) {
        return text.split('').sort().join('');
    };

function isSorted(myString) {
        return sortAlphabets(myString) == myString
    }
    
 alert("is abc sorted: " + isSorted("abc"));
  alert("is axb sorted: " + isSorted("axb"));

你已经把 return 语句放在 for 循环中,它应该在循环体之外。

您的代码也不正确。 count应该从0开始,other_count应该从1开始。

count >= str.length - 1 应该是 count < str.length - 1 (这个条件在你的代码中是完全没有必要的,因为 other_count < str.length 应该是循环中的终止条件)

other_count >= str.length 应该是 other_count < str.length

这是您更正后的代码

function is_alphabetic(str) {
  let result = true;

  for (let count = 0, other_count = 1; other_count < str.length; count++, other_count++) {
      if (str[count] > str[other_count]) {
         result = false
      }
  }

  return result;
}

console.log(is_alphabetic('abc'));

这是另一种方法

function is_alphabetic(str){
   return str.split('')
             .every((c, idx) => str[idx + 1] ? c < str[idx + 1] : true);
}

console.log(is_alphabetic('abc'));

请记住,如果您希望字符之间的比较不区分大小写,则在比较字符之前将字符串转换为小写。

您的代码中有两个问题:

  1. 您的 return 语句在您的 for 循环中。为避免此类错误,您可以获得像 prettier;
  2. 这样的代码格式化程序
  3. 您的 for 循环条件无效。请记住,for 循环语句的第二部分应该是 true 来进行迭代,而 false 来停止迭代。在这种情况下,您的条件 count >= str.length-1, other_count >= str.length 将首先评估 count >= str.length-1,由于 comma operator 而丢弃结果,评估 other_count >= str.length 立即解析为 false.

这两件事共同使您的函数永远不会 returns,javascript 运行时将其解释为 undefined

希望这可以帮助您了解问题出在哪里。但就像许多其他人指出的那样,有更好的方法来解决您要解决的问题。

您只需将字符串与其对应的 'sorted' 进行比较

let string = 'abc'.split('').join('');
let sortedString = 'abc'.split('').sort().join('');

console.log(sortedString === sortedString)

let string2 = 'dbc'.split('').join('');
let sortedString2 = 'dbc'.split('').sort().join('');

console.log(string2 === sortedString2)