rsh*_*hid 0 javascript jquery json
请参阅前面有关引用JSON(javascript)数组的元素和排序的问题.请 参阅引用JSON(Javascript)对象的元素 对JavaScript对象数组进行排序
是否可以对更复杂的javascript数组的一个分支进行排序,例如在下面的示例中按价格排序?
var homes =
{
"Agents" : [
{
"name" : "Bob Barker"
},
{
"name" : "Mona Mayflower"
}
] ,
"Listings" : [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
},
{
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
},
{
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
]
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
编辑
对困惑感到抱歉.我的意思是Javascript作为标签.(这应该是显而易见的问题)我得到了排序工作,只是在迭代数组时遇到了麻烦.
// before sort
alert(homes.Listings[0].price);
// sort
homes.Listings.sort(sort_by('price', false, parseInt));
// after sort works:
alert(homes.Listings[0].price);
// iteration does not work "$ is not defined"
$.each(homes.Listings, function(i, thisHome) {
alert(thisHome.price);
});
Run Code Online (Sandbox Code Playgroud)
该标准Array.sort采用比较器功能.使用:
function makeNumericCmp(property) {
return function (a, b) {
return parseInt(a[property]) - parseInt(b[property]);
};
}
homes.Listings.sort(makeNumericCmp('price'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3532 次 |
| 最近记录: |