日期:2014-05-16  浏览次数:20435 次

js中这个程序为什么会出错??究竟是什么含义?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
function createComparisonFunction(propertyName) {
return function(object1, object2, object3) {
var value1 = object1[propertyName];
//var value2 = object2[propertyName];
var value2 = object3[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 },
{ name: 'mr', age: 30 }
   ];
data.sort(createComparisonFunction('name'));
alert(data[0].name);

data.sort(createComparisonFunction('age'));
alert(data[0].name);
</script>
</head>

<body>
</body>
</html>




打开firebug提示
TypeError: object3 is undefined
var value2 = object3[propertyName];


但以下这个程序就OK:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
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'));