js⾯试题:⽤sort实现数组对象指定对象属性排序
补全代码,实现数组按姓名、年纪、任意字段排序。
var users = [
{ name:'freddy', age:24, score:97 },
{ name:'nick', age:18, score:87 },
{ name:'mike', age:26, score:80 },
{ name:'james', age:34, score:90 },
{ name:'curry', age:30, score:83 }
]
users.sort(byField("age"))
users.sort(byField("score"))
实现:
var users = [
{ name:'freddy', age:24, score:97 },
{ name:'nick', age:18, score:87 },
{ name:'mike', age:26, score:80 },
{ name:'james', age:34, score:90 },
{ name:'curry', age:30, score:83 }
]
function byField(m){
function Fun (a,b){
return a[m]-b[m]
}
return Fun
}
var a = users.sort(byField('age'))
console.log(a)
//var b= users.sort(byField("score"))
//console.log(b)
sort函数 js结果:
sort只接收⼀个函数

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。