如何在 JavaScript 中对字符串进行排序 [英] How to sort strings in JavaScript

查看:83
本文介绍了如何在 JavaScript 中对字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,我希望根据字符串类型的字段 attr 进行排序.我尝试使用 -

I have a list of objects I wish to sort based on a field attr of type string. I tried using -

list.sort(function (a, b) {
    return a.attr - b.attr
})

但发现 - 似乎不适用于 JavaScript 中的字符串.如何根据类型为字符串的属性对对象列表进行排序?

but found that - doesn't appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string?

推荐答案

使用 String.prototype.localeCompare 根据您的示例:

Use String.prototype.localeCompare a per your example:

list.sort(function (a, b) {
    return ('' + a.attr).localeCompare(b.attr);
})

我们强制 a.attr 为字符串以避免异常.localeCompare 已被支持 从 Internet Explorer 6 和 Firefox 1 开始.您可能还会看到使用了以下不考虑区域设置的代码:

We force a.attr to be a string to avoid exceptions. 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:

if (item1.attr < item2.attr)
  return -1;
if ( item1.attr > item2.attr)
  return 1;
return 0;

这篇关于如何在 JavaScript 中对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆