使用字符串按属性错误对对象进行数组排序

Array sorting objects by property error with strings

本文关键字:对象 数组排序 错误 字符串 属性      更新时间:2023-09-26

基本上,我正在尝试按属性对对象数组进行排序。

假设我在一个数组中有三个对象,每个对象都有一个属性views

var objs = [
    {
        views: '17'
    },
    {
        views: '6'
    },
    {
        views: '2'
    }
];

对数组objs:使用排序方法

function sortByProperty(property) {
    return function (a,b) {
        /* Split over two lines for readability */
        return (a[property] < b[property]) ? -1 : 
               (a[property] > b[property]) ? 1 : 0;
    }
}

objs.sort(sortByProperty('views'));

我预计objs现在基本上是相反的顺序,然而'17'似乎被视为小于'6''2'。我意识到这可能是因为'1'

关于解决这个问题有什么想法吗?

我意识到我可以迭代每个对象并转换为整数,但有办法避免这样做吗?

JSFiddle:http://jsfiddle.net/CY2uM/

Javascript是一种类型化语言;<表示字符串的字母排序、数字的数字排序。唯一的方法是将值强制转换为数字。一元运算符+在此处提供帮助。因此尝试

function sortByNumericProperty(property) {
    return function (a,b) {
        var av = +a[property], bv = +b[property];
        /* Split over two lines for readability */
        return (av < bv) ? -1 : 
               (av > bv) ? 1 : 0;
    }
}

但一般来说,常见的习惯用法(也记录在MDN上)

function sortByNumericProperty(property) {
    return function (a,b) {
        return a[property] - b[property];
    }
}

也应该起作用。

如果a[property]b[property]可以解析为数字

function sortByProperty(property) {
    return function (a,b) {
            return a[property] - b[property];
    }
}

在使用之前,您可能需要将值转换为整数-

function sortByProperty(property) {
    return function (a,b) {
        var x = parseInt(a[property]);  
        var y = parseInt(b[property])
        /* Split over two lines for readability */
        return (x < y) ? -1 : (x > y) ? 1 : 0;
    }
}