Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript上按对象属性对数组排序_Javascript_Arrays_Sorting - Fatal编程技术网

javascript上按对象属性对数组排序

javascript上按对象属性对数组排序,javascript,arrays,sorting,Javascript,Arrays,Sorting,我有这个代码,我需要按区域对数组的每个元素进行排序 功能矩形(底部,altura){ this.base=base; 这个。阿尔图拉=阿尔图拉; this.area=函数(){ 返回this.base*this.altura; }; this.perimeter=函数(){ 返回2*(this.base+this.altura); }; this.toString=函数(){ 返回( "(b)+ 这个基地+ “,h=”+ 这是阿尔图拉+ ’,一位女士+ 这个区域()+ ’,p='1〕+ 这个。周

我有这个代码,我需要按区域对数组的每个元素进行排序

功能矩形(底部,altura){
this.base=base;
这个。阿尔图拉=阿尔图拉;
this.area=函数(){
返回this.base*this.altura;
};
this.perimeter=函数(){
返回2*(this.base+this.altura);
};
this.toString=函数(){
返回(
"(b)+
这个基地+
“,h=”+
这是阿尔图拉+
’,一位女士+
这个区域()+
’,p='1〕+
这个。周长()+
')'
);
};
}
变量矩形=[
新矩形(1,1),
新矩形(2,2.05),
新矩形(2,5),
新矩形(1,3),
新矩形(4,4),
新矩形(2,8)
];
我需要首先在javascript的数组类中声明函数,然后使用sort()方法对其进行排序

array.prototype.ordenaPerArea=function(){
};

我怎样才能做到这一点呢?

您可以使用减去面积来进行比较

功能矩形(底部,altura){
this.base=base;
这个。阿尔图拉=阿尔图拉;
this.area=函数(){
返回(this.base*this.altura);
}
this.perimeter=函数(){
返回2*(this.base+this.altura);
}
this.toString=函数(){
return“(b=“+this.base+”,h=“+this.altura+”,a=”+
this.area()+”,p=“+this.perimeter()+”;
}
}
变量矩形=[
新矩形(1,1),
新矩形(2,2.05),
新矩形(2,5),
新矩形(1,3),
新矩形(4,4),
新矩形(2,8)
];
矩形。排序((a,b)=>a.area()-b.area());

forEach(x=>console.log(x.toString())我想你要找的是:

方法修改原始数组:
功能矩形(底部,altura){
this.base=base;
这个。阿尔图拉=阿尔图拉;
this.area=函数(){
返回this.base*this.altura;
};
this.perimeter=函数(){
返回2*(this.base+this.altura);
};
this.toString=函数(){
返回(
"(b)+
这个基地+
“,h=”+
这是阿尔图拉+
’,一位女士+
这个区域()+
’,p='1〕+
这个。周长()+
')'
);
};
}
变量矩形=[
新矩形(1,1),
新矩形(2,2.05),
新矩形(2,5),
新矩形(1,3),
新矩形(4,4),
新矩形(2,8)
];
log('rectangles(before):');
forEach(item=>console.log(item.area());
Array.prototype.ordenaPerArea=函数(){
返回此.sort(函数(rectA,rectB){
返回rectA.area()-rectB.area();
});
}
矩形。ordenaPerArea();
log('矩形(后面):');

forEach(item=>console.log(item.area())
是否应该
array.prototype.ordenaPerArea()
直接修改原始数组或创建有序副本,而不修改原始数组?顺便问一下,您确定向阵列原型添加方法是最好的方法吗?不使用“正常功能”(我指的是类似
ordenaPerArea(arr)
)的功能)有什么特殊原因吗?@iota是的,非常完美,谢谢,但另一个功能更完整!