在线文档教程

Intl.collator.compare

Intl.collator.compare

Intl.Collator.prototype.compare属性返回一个getter函数,该函数根据此Collator对象的排序顺序比较两个字符串。

语法

collator.compare(string1, string2)

参数

string1string2字符串相互比较。

描述

这个函数将会返回一个数字,这个数字是按顺序比较string1string2的字符:如果string1的字符在string2之前则会返回负数,如果string1的字符在string2之后则会返回正数; 如果它们别认为是相等的则会返回0

例子

使用compare进行数组排序

使用comparegetter 返回的函数对数组进行排序。请注意,该函数与所选的collat​​or相关,所以它可以直接传递给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搜索

使用comparegetter 返回的函数来查找数组中的匹配字符串:

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"

规范

SpecificationStatusComment
ECMAScript Internationalization API 1.0 (ECMA-402)The definition of 'Intl.Collator.prototype.compare' in that specification.StandardInitial 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

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support24(Yes)29 (29)1115No support

FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic supportNo support26(Yes)56.0 (56)No supportNo supportNo support