鉴于以下学生的记录数组 - 您如何根据年龄使用Javascript按升序对其进行排序?
students = [{
name: "timothy",
age: "9"},
{
name: "claire",
age: "12"},
{
name: "michael",
age: "20"}]
答案 0 :(得分:1)
要按年龄按升序排序,请使用Array.sort
和自定义比较器功能:
students.sort(function (a, b)
{
return a.age - b.age;
});
// students will be
[{name: "timothy", age: "9"},
{name: "claire", age: "12"},
{name: "michael", age: "20"}]
答案 1 :(得分:0)
按年龄:
students = students.sort(function(a, b) {
return parseFloat(a.age) - parseFloat(b.age);
});
答案 2 :(得分:0)
student.sort(function(a,b){
if (a.name > b.name)
return -1;
return 1;
});
答案 3 :(得分:0)
阅读这个例子:
var marks = new Array(10,12,11,20,2);
for(var i=0;i<marks .length;i++) //Hold the first element
{
for(var j=i+1;j<marks.length;j++) //Hold the next element from the first element
{
if(Number(marks[i]) > Number(marks[j])) //comparing first and next element
{
tempValue = marks[j];
marks[j] = marks[i];
marks[i] = tempValue;
}
}
}
document.write(marks);
答案 4 :(得分:0)
students.sort(function(a,b){
if (+a.age > +b.age) return 1;
return -1;
});
// Now the object is ordered by age (min to max)
如果您想知道, + a.age 与数字(a.age)
相同