数组对象排序
<h3>对象可以按照某个属性排序</h3>
<blockquote>
<p>思路:sort() 可以字母排序,也可以数字排序
字母排序:先把取到的值按照转化成大写,然后才能进行排序
数值排序:可以直接按照大小来排序</p>
</blockquote>
<p>关于sort()排序可以参考以下链接
<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort</a></p>
<pre><code class="language-javascript">var students = [
{ name: 'zspang', age: 32 },
{ name: 'Panda', age: 30 },
{ name: 'PanPaN', age: 21 },
{ name: 'King', age: 45 }
]
function sortByKey(arr, key) {
return arr.sort(function (a, b) {
var x = a[key];
var y = b[key];
if(typeof x === "string" && typeof y === "string"){
x= x.toUpperCase();
y = y.toUpperCase();
}
return ((x < y) ? -1 : ((x > y) ? 1 : 0))
})
}
console.log(sortByKey(students, "age")); //得到排序后的结果
console.log(sortByKey(students, "name")); //得到排序后的结果</code></pre>