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)
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()
我的机器快一个数量级.
在+
保证答案永远是数字,而不是布尔值.
小智 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
使其进行逻辑数比较
归档时间: |
|
查看次数: |
109220 次 |
最近记录: |