The below is the code:
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{
return 0;
}
};
}
var data = [{name: "Zachary", age: 28}, {name: "Nicholas", age: 29}];
data.sort(createComparisonFunction("name"));
alert(data开发者_如何学JAVA[0].name);
data.sort(createComparisonFunction("age"));
alert(data[0].name);
As you can see the createCompatisonFunction is filled in with value called name and as you can see inside this function, there's object1 and object2. Can I ask what does these arguments pass in with? Do you catch me?
when sorting elements in data
the sorting algorithm will have to perform elementary comparison between two elements to determine which one is greater than the other. The sort
method of array objects, supplies the comparison function the two objects that it wants to compare. Basically you are defining a < operator of sorts for your object.
Array.prototype.sort
accepts a function that is defined as such
function(left, right) {
return new Number();
}
The sorting function is passed two elements of the array and you return a number stating in which order they should go.
If the left element needs to go before right then just return -1
otherwise return 1
if right is supposed to come before left.
return 0
if it does not matter.
In your case object1
and object2
are {name: "Zachary", age: 28}
and {name: "Nicholas", age: 29}
respectively.
Your code for the function createComparisonFunction
is a function that returns a function.
In essence your code is no different than the following expanded out:
var data = [{name: "Zachary", age: 28}, {name: "Nicholas", age: 29}];
data.sort(function(object1, object2){
var value1 = object1["name"];
var value2 = object2["name"];
if(value1 < value2){
return -1;
}else if(value1 > value2){
return 1;
}else{
return 0;
}
});
alert(data[0].name);
data.sort(function(object1, object2){
var value1 = object1["age"];
var value2 = object2["age"];
if(value1 < value2){
return -1;
}else if(value1 > value2){
return 1;
}else{
return 0;
}
});
alert(data[0].name);
And the purpose of creating the createComparisonFunction(propertyName)
is to refactor copy and pasted code into one area allowing for easier management of code. Also note if your data object also contained a propery called "lastname" this one function could also be used to sort by LastName. Basically the one function is far more robust than copying and pasting code.
精彩评论