有时我在设计一些很多重复单元时,就会把重复的数据作为一个对象,然后将所有的单元作为一个JSON对象数组进行存储,然后自然地就会遇到排序的问题,这个排序其实也是比较常见的功能之一。此时就需要将JSON对象数组进行排序,然后将排序之后的JSON数组写入网页中。
使用JavaScript中数组的sort方法实现:
(1) 首先定义排序是升序还是降序:
var sortIndex = "discount";
var asce = function (x,y) {
return (x[sortIndex] > y[sortIndex])? 1:-1
};
var desc = function (x,y) {
return (x[sortIndex] < y[sortIndex])? 1:-1
};
asce代表升序排序,desc代表降序排序,然后sortIndex代表我们排序的依据,这里的discount
是JSON数组中的某个属性,代表根据discount
来进行排序。
arrayName.sort(asce);
将我们指定的升序或降序定义函数传入sort
函数中,然后就可以对 arrayName
这个数组按照我们的需求进行排序了。
一些有关的代码:
(1)当我们需要重新载入 (append) 排序之后的信息时,就需要将之前的信息删除,这里可以使用empty方法来清空父容器中的内容:
$(".containerClass").empty();
containerClass
是指盛放一个个子信息单元的父容器
(2)将JSON对象数组写入网页中:
这里举一个购物网站的例子
JSON数组内容:
里面是一些商品的图片以及价格等信息
var goodLists = [
{
"img" : "<img src=\"../Picture/secondary-goods-content1.jpg\" style=\"width: 218px;\" alt=\"\">", "Price" : 179,"tempPrice":"798","discount":2.2,"description":" 恒源祥 | 2019春季新款V领桑蚕丝针织衫开衫女式针织衫"},
{
"img" : "<img src=\"../Picture/secondary-goods-content5.jpg\" style=\"width: 218px;\" alt=\"\">", "Price" : 29, "tempPrice" : "99.9", "discount" : 1.36, "description" : "云麦 握力圈减压硅胶握力器手指康复专业训练手力男女健身便携小巧"},
{
"img" : "<img src=\"../Picture/secondary-goods-content4.jpg\" style=\"width: 218px;\" alt=\"\">", "Price" : 999, "tempPrice" : "1999", "discount" : 6.5, "description" : "奥义 【口碑爆款】瑜伽脚蹬拉力器家用运动健身减肥仰卧起坐女器材用品"},
{
"img" : "<img src=\"../Picture/secondary-goods-content3.jpg\" style=\"width: 218px;\" alt=\"\">", "Price" : 100, "tempPrice" : "120.5", "discount" : 7, "description" : "李宁 仰卧起坐辅助器材家用健身瘦肚子脚蹬拉力器瑜伽女卷腹弹力绳"},
{
"img" : "<img src=\"../Picture/secondary-goods-content2.jpg\" style=\"width: 218px;\" alt=\"\">", "Price" : 199, "tempPrice" : "299", "discount" : 3.1415926, "description"