以下是按某些属性对对象数组进行排序的函数。
function createCompareFunc(propertyName){
return function(obj1, obj2){
var val1=obj1[propertyName];
var val2=obj1[propertyName];
return val1-val2;
}
}
var data=[{name:'a', age:12},{name:'b',age:5}];
console.log(typeof data[0]['age']); //number
console.log(data.sort(createCompareFunc('name')));
//[Object{name="a", age=12},Object{name="b",age=5}]
console.log(data.sort(createCompareFunc('age')));
//[Object{name="a", age=12},Object{name="b",age=5}], but I want to get '[Object{name="b",age=5},Object{name="a", age=12}]'
号码有什么问题?
答案 0 :(得分:0)
Typo obj1而不是第6行的obj2。
答案 1 :(得分:0)
以下是代码及其“为您提出的问题所做的工作:
function createCompareFunc(propertyName){
return function(obj1, obj2){
val1=obj1[propertyName];
val2=obj2[propertyName];
return val1-val2;
}
}
var data=[{name:'a', age:12},{name:'b',age:5}];
console.log(typeof data[0]['age']);
console.log(data.sort(createCompareFunc('age')));
console.log(typeof data[0]['name']);
console.log(data.sort(createCompareFunc('name')));
有一个逻辑错误,我想你没有注意到它。你不能在javascript中将字符串与 - 运算符进行比较,因此将属性类型作为参数传递给createCompareFunc(propertyName,type),并根据它进行排序。例如:
createCompareFunc(propertyName,type)
{
//function
//sorting based on type of element
}
createCompareFunc('age',typeof data[0]['age']);