js 数组 排序

本文介绍了JavaScript中数组排序的基本方法及如何使用sort()函数对复杂数组进行定制化排序。通过示例展示了基本数组与对象数组的排序技巧。

一.数组的排序。数组排序一般用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));

 就如这过例子一样,就可以进行排序了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值