有没有JavaScript strcmp()?

123 javascript string strcmp

任何人都可以为我验证这个吗?JavaScript没有strcmp()的版本,所以你必须写出类似的东西:

 ( str1 < str2 ) ? 
            -1 : 
             ( str1 > str2 ? 1 : 0 );
Run Code Online (Sandbox Code Playgroud)

new*_*cct 127

关于什么

str1.localeCompare(str2)
Run Code Online (Sandbox Code Playgroud)

  • 你在看什么标准?它似乎是在ECMA-262标准第15.5.4.9节以及mozilla Javascript参考中(https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String#Methods_unrelated_to_HTML) (8认同)
  • `localeCompare()`有时在每个浏览器上表现不同. (3认同)
  • @VardaElentári:仅适用于给定语言环境中没有词汇顺序的字符。对于*这样做*的字符和不限制它们使用 Unicode 部分的浏览器,结果是一致的并且[由 ECMA-402 和 Unicode 定义](http://ecma-international.org/ecma-402/3.0/ index.html#sec-implementation-dependency)。 (2认同)

Est*_*ber 37

正如你所指出的,Javascript没有它.

快速搜索出现了:

function strcmp ( str1, str2 ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Waldo Malqui Silva
    // +      input by: Steve Hilder
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: gorthaur
    // *     example 1: strcmp( 'waldo', 'owald' );
    // *     returns 1: 1
    // *     example 2: strcmp( 'owald', 'waldo' );
    // *     returns 2: -1

    return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}
Run Code Online (Sandbox Code Playgroud)

来自http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/

当然,如果需要,您可以添加localeCompare:

if (typeof(String.prototype.localeCompare) === 'undefined') {
    String.prototype.localeCompare = function(str, locale, options) {
        return ((this == str) ? 0 : ((this > str) ? 1 : -1));
    };
}
Run Code Online (Sandbox Code Playgroud)

并且str1.localeCompare(str2)无处不在,无需担心本地浏览器随附了它.唯一的问题是你必须添加支持locales,options如果你关心它.


1''*_*1'' 20

localeCompare()很慢,所以如果你不关心非英文字符串的"正确"排序,请尝试原始方法或看起来更干净:

str1 < str2 ? -1 : +(str1 > str2)
Run Code Online (Sandbox Code Playgroud)

这比localeCompare()我的机器快一个数量级.

+保证答案永远是数字,而不是布尔值.

  • 这是一个更清晰的表达式:`(str1> str2) - (str1 <str2)` (5认同)
  • @stackunderflow我在排序功能中成功使用它.您遇到的错误是什么? (2认同)
  • 还有一件事(我现在正在编写的代码中使用它,所以我一直在完善它):请注意这是一个区分大小写的比较('Foo'将在'bar'之前出现但是'酒吧'将来'foo').这与OP关于strcmp的问题相对应,但很多人可能会来这里寻找与案例无关的比较. (2认同)

小智 5

var strcmp = new Intl.Collator(undefined, {numeric:true, sensitivity:'base'}).compare;
Run Code Online (Sandbox Code Playgroud)

用法: strcmp(string1, string2)

结果:1表示string1较大,0表示相等,-1表示string2较大。

这比 String.prototype.localeCompare

此外,numeric:true使其进行逻辑数比较