<! DOCTYPE html><html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div>Sort () sorts an array, does not create new memory, and swaps the elements of the existing array</div>
		<div id="showBox">1, simple array simple sort<script type="text/javascript">
				var arrSimple = new Array(1.8.7.6);
				arrSimple.sort();
				document.writeln(arrSimple.join());
			</script>
		</div>
		<div>2, simple array custom sort<script type="text/javascript">
				var arrSimple2 = new Array(1.8.7.6);
				arrSimple2.sort(function(a, b) {
					return b - a
				});
				document.writeln(arrSimple2.join());
			</script>
			<div>Return (a,b); return (a,b); Reutrn < 0; When a=b, there is browser compatibility to simplify: a-b outputs are sorted from smallest to largest, and B-A outputs are sorted from largest to smallest.</div>3, simple object List custom attribute sort<script type="text/javascript">
						var objectList = new Array(a);function Persion(name, age) {
							this.name = name;
							this.age = age;
						}
						objectList.push(new Persion('jack'.20));
						objectList.push(new Persion('tony'.25));
						objectList.push(new Persion('stone'.26));
						objectList.push(new Persion('mandy'.23));
						// Sort by age
						objectList.sort(function(a, b) {
							return a.age - b.age
						});
						for (var i = 0; i < objectList.length; i++) {
							document.writeln('<br />age:' + objectList[i].age + ' name:' + objectList[i].name);
						}
					</script>
				</div>
				<div>Sort editable attributes by simple object List<script type="text/javascript">
						var objectList2 = new Array(a);function WorkMate(name, age) {
							this.name = name;
							var _age = age;
							this.age = function() {
								if (!arguments) {
									_age = arguments[0];
								} else {
									return _age;
								}
							}

						}
						objectList2.push(new WorkMate('jack'.20));
						objectList2.push(new WorkMate('tony'.25));
						objectList2.push(new WorkMate('stone'.26));
						objectList2.push(new WorkMate('mandy'.23));
						// Sort by age
						objectList2.sort(function(a, b) {
							return a.age() - b.age();
						});
						for (var i = 0; i < objectList2.length; i++) {
							document.writeln('<br />age:' + objectList2[i].age() + ' name:' + objectList2[i].name);
						}
					</script>
				</div>
	</body>
</html>

Copy the code