Open IVYGOU opened 8 years ago
function createComparisonFunction(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(value1 = value2) { return 0; } }; } var data=[{name:"Mike",age:21},{name:"Ivy",age:25}]; data.sort(createComparisonFunction("name")); console.log(data[0].name);//Ivy data.sort(createComparisonFunction("age")); console.log(data[0].name);//Mike
方括号表示的属性可以是变量,点表示的属性值是固定的不可变。