js使用sort方法對數組排序

在這裏插入圖片描述

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<script>
		let a = [
			{
				label:'武漢',
				index:5
			},
			{
				label:'上海',
				index:4
			},
			{
				label:'成都',
				index:1
			},
			{
				label:'深圳',
				index:9
			}
		]

		function compare(arg) {
		    return function(a, b) {
		        return a[arg] - b[arg];
		    }
		}
		arr = a.sort(compare('index'));
		console.log(arr)
	</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章