js 数组 排序
程序员文章站
2022-03-31 16:00:18
...
一.数组的排序。数组排序一般用sort()方法就可以解决了。
var id=['001','010','005','006']; id.sort(); console.log(JSON.stringify(id));//["001","005","006","010"]
但是有许多复杂的数组就不能这样直接排序了。不过我们可以通过改造sort()方法来,进行排序。
var goods_info=[ {barcode:"005", type: '食品', name: '方便面', price: '4.5', unit: '袋'}, {barcode:"000", type: '饮料', name: '可口可乐', price: '3', unit: '瓶'}, {barcode:"002", type: '水果', name: '苹果', price: '5.5', unit: '斤'}, {barcode:"001", type: '饮料', name: '雪碧', price: '3', unit: '瓶'}, {barcode:"004", type: '生活用品', name: '电池', price: '2', unit: '个'}, {barcode:"003", type: '水果', name: '荔枝', price: '15', unit: '斤'},]; goods_info.sort(function(a,b){ return a.barcode>b.barcode ? 1 : -1; }); console.log(JSON.stringify(goods_info));
就如这过例子一样,就可以进行排序了。