Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中对字符串排序(How to sort strings in JavaScript)

I have a list of objects I wish to sort based on a field attr of type string.(我有一个对象列表,希望根据字符串类型的字段attr进行排序。)

I tried using -(我尝试使用-) list.sort(function (a, b) { return a.attr - b.attr }) but found that - doesn't appear to work with strings in JavaScript.(但发现-在JavaScript中似乎不适用于字符串。) How can I sort a list of objects based on an attribute with type string?(如何根据具有字符串类型的属性对对象列表进行排序?)   ask by airportyh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use String.prototype.localeCompare a per your example:(根据您的示例使用String.prototype.localeCompare a:)

list.sort(function (a, b) { return ('' + a.attr).localeCompare(b.attr); }) We force a.attr to be a string to avoid exceptions.(我们强制a.attr为字符串以避免异常。) localeCompare has been supported since Internet Explorer 6 and Firefox 1. You may also see the following code used that doesn't respect a locale:(自Internet Explorer 6和Firefox 1开始支持localeCompare 。您可能还会看到以下使用的不符合语言环境的代码:) if (item1.attr < item2.attr) return -1; if ( item1.attr > item2.attr) return 1; return 0;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...