如何在JavaScript中对字符串排序
16lz
2021-01-22
I have a list of objects I wish to sort based on a field attr
of type string. I tried using -
我有一个对象列表,我希望根据类型为string的字段attr进行排序。我试着用,
list.sort(function (a, b) {
return a.attr - b.attr
})
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?
但是发现-在JavaScript中似乎不能处理字符串。如何基于具有字符串类型的属性对对象列表进行排序?
8 个解决方案
#1
352
Use String.prototype.localeCompare
a per your example:
使用String.prototype。localeCompare符合你的例子:
list.sort(function (a, b) {
return ('' + a.attr).localeCompare(b.attr);
})
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:
我们迫使。attr为字符串,以避免异常。从Internet Explorer 6和Firefox 1开始就支持localeCompare。您可能还会看到下面使用的不尊重语言环境的代码:
if (item1.attr < item2.attr)
return -1;
if ( item1.attr > item2.attr)
return 1;
return 0;
更多相关文章
- JavaScript循环输入创建一个对象数组
- NodeJS - 解析JSON(只有字符串或数字)
- 如何从json对象获取匹配元素的索引?
- JavaScript:使用函数参数检索javascript对象键
- JavaScript 对象属性作实参以及实参对象的callee属性
- JavaScript中的对象描述符
- javascripterror 为空或不是对象.
- JavaScript中的数学对象中的方法
- Javascript知识汇总------面向对象中继承(未完成)