我正在使用this solution對對象數組進行排序。這是功能:使用逗號分隔的價格字符串按數字順序排列對象數組
function sortJsonArrayByProperty(objArray, prop, direction){
if (arguments.length<2) throw new Error("sortJsonArrayByProp requires 2 arguments");
var direct = arguments.length>2 ? arguments[2] : 1; //Default to ascending
if (objArray && objArray.constructor===Array){
var propPath = (prop.constructor===Array) ? prop : prop.split(".");
objArray.sort(function(a,b){
for (var p in propPath){
if (a[propPath[p]] && b[propPath[p]]){
a = a[propPath[p]];
b = b[propPath[p]];
}
}
// convert numeric strings to integers
a = a.match(/^\d+$/) ? +a : a;
b = b.match(/^\d+$/) ? +b : b;
return ((a < b) ? -1*direct : ((a > b) ? 1*direct : 0));
});
}
}
這是一個很好的解決方案。
但是我有一個列一個問題,即存儲價格格式爲:
950,75 1234,99 500,00
所以,我有一個逗號分隔小數值。 然後,不是這個順序:
222,55 550,00 2000,99 3000,00
我越來越:
2000,99 222,55 3000,00 550,00
我想在做這部分做一些修改:
a = a.match(/^\d+$/) ? +a : a;
b = b.match(/^\d+$/) ? +b : b;
但是,這ISN」不工作。怎麼了?
有沒有這樣的事,作爲一個 「JSON對象」。 JSON是JavaScript對象的有限字符串序列化。 – Touffy
您正在排序的內容不是JSON對象。這是一個包含JavaScript對象的JavaScript數組。 JSON是用於數據交換的*文本符號。如果你正在編寫代碼,並且你沒有處理*字符串*,那麼你並沒有處理JSON。 –
爲什麼不用''替換逗號',',''並且這樣做? –