数组排序sort
<script type="text/javascript">、 var arrs = [ { name:'李老汉', age:'5' },{ name:'隔壁老王', age:'45' }, { name:'傻狗子', age:'3' }, { name:'小马哥', age:'56' }, { name:'李云龙', age:'66' } ]; function arrtSort(arr){ var compare = function (prop) { return function (obj1, obj2) { var val1 = obj1[prop]; var val2 = obj2[prop]; if (!isNaN(Number(val1)) && !isNaN(Number(val2))) { val1 = Number(val1); val2 = Number(val2); } if (val1 > val2) { return -1; } else if (val1 < val2) { return 1; } else { return 0; } } } return arr.sort(compare("age")); } let newarr = arrtSort(arrs); console.log(newarr) </script>
结果: