此比较函数为Array对象的sort()方法用来排序,所接收的函数参数
一:最简单的比较函数
function compareFunction(a, b) {
return a - b;
}//适用于普通的 数值和字符串 的 数组元素
二:最标准的比较函数
function compareFunction(a, b) {
if(a < b) { return -1; }
else if (a > b) { return 1; }
else { return 0; }
}
三:适用--包含对象元素的数组
function compareFunction(propertyName) {
return function(object1, object2) {
var value1 = object1[propertyName];
var value2 = object2[propertyName];
//需要注意的是 上面两行代码 必须用方括号访问对象,只能方括号表示法才能访问变量。
if(value1 < value2) { return -1; }
else if(value1 > value2) { return 1; }
else { return 0 }
}
}
var arr = [{name:"Greg",age:41, job:"Doctor"},
{name:"Bill",age:56, job:"Engineer"},
{name:"Mark",age:29, job:"Enterpriser"}];
arr.sort(compareFunction("age"));
/*输出[{name: "Mark", age: 29, job: "Enterpriser"},
{name: "Greg", age: 41, job: "Doctor"},
{name: "Bill", age: 56, job: "Engineer"}] */
arr.sort(compareFunction("name"));
/*输出[{name: "Bill", age: 56, job: "Engineer"},
{name: "Greg", age: 41, job: "Doctor"},
{name: "Mark", age: 29, job: "Enterpriser"}]
*/
第三部分代码涉及到方括号表示法和点表示法的区别访问对象的区别
请阅读我的>>访问对象属性时点表示法和方括号表示法的区别
网友评论