Intl.collator.compare
Intl.collator.compare
该Intl.Collator.prototype.compare
属性返回一个getter函数,该函数根据此Collator
对象的排序顺序比较两个字符串。
语法
collator.compare(string1, string2)
参数
string1string2
字符串相互比较。
描述
这个函数将会返回一个数字,这个数字是按顺序比较string1
和string2
的字符:如果string1
的字符在string2
之前则会返回负数,如果string1
的字符在string2
之后则会返回正数; 如果它们别认为是相等的则会返回0
例子
使用compare进行数组排序
使用compare
getter 返回的函数对数组进行排序。请注意,该函数与所选的collator相关,所以它可以直接传递给Array.prototype.sort()
。
var a = ['Offenbach', 'Österreich', 'Odenwald'];
var collator = new Intl.Collator('de-u-co-phonebk'
a.sort(collator.compare
console.log(a.join(', ')
// → "Odenwald, Österreich, Offenbach"
使用compare在array搜索
使用compare
getter 返回的函数来查找数组中的匹配字符串:
var a = ['Congrès', 'congres', 'Assemblée', 'poisson'];
var collator = new Intl.Collator('fr', { usage: 'search', sensitivity: 'base' }
var s = 'congres';
var matches = a.filter(v => collator.compare(v, s) === 0
console.log(matches.join(', ')
// → "Congrès, congres"
规范
Specification | Status | Comment |
---|---|---|
ECMAScript Internationalization API 1.0 (ECMA-402)The definition of 'Intl.Collator.prototype.compare' in that specification. | Standard | Initial definition. |
ECMAScript Internationalization API 2.0 (ECMA-402)The definition of 'Intl.Collator.prototype.compare' in that specification. | Standard | |
ECMAScript Internationalization API 4.0 (ECMA-402)The definition of 'Intl.Collator.prototype.compare' in that specification. | Draft | |
浏览器兼容性
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 24 | (Yes) | 29 (29) | 11 | 15 | No support |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | No support | 26 | (Yes) | 56.0 (56) | No support | No support | No support |