gpt4 book ai didi

javascript:如何按年龄对员工对象数组进行排序

转载 作者:行者123 更新时间:2023-12-02 19:33:31 24 4
gpt4 key购买 nike

我正在尝试按年龄对员工对象数组进行排序,并且得到以下输出:

[object Object],[object Object],[object Object],[object Object]

但是,当我将员工数组替换为数字数组时,代码可以正常工作,例如:var 点=[2,10,7,8]

有人可以告诉我哪里出错了吗?谢谢。

以下是我的代码:

<script type="text/javascript">

function sortFunc(){

var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}

employees.sort(function(a, b){
return a.age-b.age
// return a-b;
})
document.getElementById("disp").innerHTML=employees;

}

</script>
</head>
<body>
<div id="disp">Click the button below to sort.</div>
<button onclick="sortFunc()">Sort Now</button>
</body>

最佳答案

排序工作正常。您的输出方式不正确。

尝试使用循环而不是innerHTML将其添加到页面。

var out="";
for(var i=0;i<employees.length;i++){
out+="<p>"+employees[i]['age']+", "+employees[i]['name']+"</p>\n";
}

document.getElementById("disp").innerHTML=out;

您也可以这样定义对象:

var employees=[
{name:"George", age:32, retiredate:"March 12, 2014"},
{name:"Edward", age:17, retiredate:"June 2, 2023"},
{name:"Christine", age:58, retiredate:"December 20, 2036"},
{name:"Sarah", age:62, retiredate:"April 30, 2020"}
]

干杯

G.

关于javascript:如何按年龄对员工对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11223179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com