数组对象方法排序:
function sortByKey(array,key){
return array.sort(function(a,b){
var x=a[key];
var y=b[key];
return ((x<y)?-1:((x>y)?1:0));
});
}
示例如下:该例子配合使用的是vue
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-for</title>
<script src="../assets/js/vue.js"></script>
</head>
<body>
<h1>v-for</h1>
<hr>
<div id="app">
<ul>
<li v-for="item in setItems">{{item}}</li>
</ul>
<hr>
<ul>
<li v-for="(student,index) in setStudents">
{{index+1}}:{{student.name}}-{{student.age}}
</li>
</ul>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
items: [53,23,7,14],
students:[
{name:'tpp', age: 25},
{name:'ldh', age: 27},
{name:'jxy', age: 24},
{name:'whh', age: 28},
{name:'xuj', age: 4}
]
},
computed:{//计算属性,会保护items原有的值,所以需要重新定义名字
setItems:function(){
return this.items.sort(sortNum);
},
setStudents: function(){
return sortByKey(this.students,'age')
}
}
});
function sortNum(a,b){//数字从小到大的排序函数
return a-b;
};
//数组对象方法排序:
function sortByKey(array,key){
return array.sort(function(a,b){
var x=a[key];
var y=b[key];
return ((x<y)?-1:((x>y)?1:0));
});
}
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-for</title>
<script src="../assets/js/vue.js"></script>
</head>
<body>
<h1>v-for</h1>
<hr>
<div id="app">
<ul>
<li v-for="item in setItems">{{item}}</li>
</ul>
<hr>
<ul>
<li v-for="(student,index) in setStudents">
{{index+1}}:{{student.name}}-{{student.age}}
</li>
</ul>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
items: [53,23,7,14],
students:[
{name:'tpp', age: 25},
{name:'ldh', age: 27},
{name:'jxy', age: 24},
{name:'whh', age: 28},
{name:'xuj', age: 4}
]
},
computed:{//计算属性,会保护items原有的值,所以需要重新定义名字
setItems:function(){
return this.items.sort(sortNum);
},
setStudents: function(){
return sortByKey(this.students,'age')
}
}
});
function sortNum(a,b){//数字从小到大的排序函数
return a-b;
};
//数组对象方法排序:
function sortByKey(array,key){
return array.sort(function(a,b){
var x=a[key];
var y=b[key];
return ((x<y)?-1:((x>y)?1:0));
});
}
</script>
</body>
</html>