1

我有一个像这样的带有十进制值的数组

["$79.34", "$99.23", "$149", "$139.34", "$379", "$199.00", "$5", "$9", "$14", "$39", "$59", "$24", "$29", "$189", "$10,$20", "$500", "$1", "$4", "$8.66", "$2", "$19", "$18", "$11", "$15", "$40", "$89", "$100", "$400.15", "$30,$119", "$15,$30"]

对于我的商店,我不知道如何使用 javascript 对它们进行排序?(或任何与此相关的$符号)似乎对我造成了问题?

我该如何解决这个问题?

4

2 回答 2

3
var prices = [...]
prices.sort(function(a,b) { return (a.substring(1)) - (b.substring(1)); })

会成功的。

于 2012-06-01T21:05:45.453 回答
0

编辑:我写了一个JSFiddle 来证明这一点

function sortPrices(priceStrings) 
{
    //first sanitize the data
    for (var i = 0; i < priceStrings.length; i++) 
    {
        if (priceStrings[i].toString().search(",") != -1) 
        {
            var splits = priceStrings[i].toString().split(",");
            priceStrings.splice(i, 1)
            priceStrings = priceStrings.concat(splits);
            i--;
        }
    }
    var prices = [];
    for (var i = 0; i < priceStrings.length; i++) 
    {
        priceStrings[i] = priceStrings[i].toString().replace("$", "");
        prices.push(parseFloat(priceStrings[i]));
    }

    prices.sort(function(a,b){return a - b});

    return prices;
}​
于 2012-06-01T21:02:50.040 回答