js数组排序

web开发中,获取的json数组对象,有时候需要按不同的字段排序,为了减少对服务器请求的次数,可以使用js的数组排序方法sort()对数组排序。

一.简单的数字数组排序
	1.1 升序
		var array=[5,3,1,2,7,4];
		var resulet=array.sort();
		console.log(resulet);
		输出结果:[1, 2, 3, 4, 5, 7]
	1.2 降序
		var array=[5,3,1,2,7,4];
		var resulet=array.sort().reverse();
		console.log(resulet);
		输出结果:[7, 5, 4, 3, 2, 1]
二.简单的英文单词数组排序(按首个英文字母排序)
	2.1 升序
		var array=['call','hello','apple','open'];
		var resulet=array.sort();
		console.log(resulet);
		输出结果:["apple", "call", "hello", "open"]
	2.2 降序
		var array=['call','hello','apple','open'];
		var resulet=array.sort().reverse();
		console.log(resulet);
		输出结果:["open", "hello", "call", "apple"]
三.简单的中文名数组按第一个字拼音排序,如果拼音相同,则按照笔画排序
	3.1 升序
		var array=['李鹏','李彭','张奎','王航','林格'];
		function complete(x,y){
			return x.localeCompare(y,"zh");
		}
		var resulet=array.sort(complete);
		console.log(resulet);
		输出结果:["李彭", "李鹏", "林格", "王航", "张奎"]
	3.2 降序
		var array=['李鹏','李彭','张奎','王航','林格'];
		function complete(x,y){
			return y.localeCompare(x,"zh");
		}
		var resulet=array.sort(complete);
		console.log(resulet);
		输出结果:["张奎", "王航", "林格", "李鹏", "李彭"]
四.数组对象排序
	4.1按照数组对象age属性升序
		var array=[ {"name":"张奎",age:19},
					{"name":"王海",age:15},
					{"name":"林英",age:17},
					{"name":"李武",age:13}];
		var resulet=array.sort(complete);
		function complete(x,y){
			if(x.age>y.age){
				return 1;
			}else if(x.agey.age){
				return -1;
			}else if(x.age

你可能感兴趣的:(JavaScript知识)