js中函数可以作为参数和返回值,来看看下面的排序
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function Student(name, height, weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
//创建对象
var stu1 = new Student("kk", "175", "55kg");
var stu2 = new Student("kl", "185", "65kg");
var stu3 = new Student("w", "170", "50kg");
// 将对象放入数组中
var arr = [stu1, stu2, stu3];
// 将函数作为返回值
function f1(attr) {
return function (str1, str2) {
if(str1[attr] > str2[attr]) {
return 1;
}else if (str1[attr] === str2[attr]) {
return 0;
}else {
return -1;
}
}
}
//接受返回值--函数
//根据height来进行排序
var ff = f1("height");
// 排序,将函数作为参数
arr.sort(ff);
for(var i = 0; i < arr.length; i++) {
console.log(arr[i].name+"==="+arr[i].height+"==="+arr[i].weight);
}
</script>
</body>
</html>
显示的结果: