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;

更多相关文章

  1. JavaScript循环输入创建一个对象数组
  2. NodeJS - 解析JSON(只有字符串或数字)
  3. 如何从json对象获取匹配元素的索引?
  4. JavaScript:使用函数参数检索javascript对象键
  5. JavaScript 对象属性作实参以及实参对象的callee属性
  6. JavaScript中的对象描述符
  7. javascripterror 为空或不是对象.
  8. JavaScript中的数学对象中的方法
  9. Javascript知识汇总------面向对象中继承(未完成)

随机推荐

  1. 去掉android的屏幕上的title bar
  2. asdasdas
  3. android 表单布局 左右布局
  4. Android设计模式系列
  5. Android 读取和保存文件(手机内置存储器)
  6. Simple Gestures on Android
  7. Android入门学习七:基本控件学习
  8. Android 获取WIFI MAC地址的方法
  9. 2011.07.06(2)——— android apiDemos 之
  10. Android-TextView多行本文滚动轻松实现