SOURCE

console 命令行工具 X clear

                    
>
console
var arr = [23, 22, 26, 21];

var list = [
  { name: '李四', id: 2, age: 23 },
  { name: '张三', id: 1, age: 22 },
  { name: '赵六', id: 4, age: 26 },
  { name: '王五', id: 3, age: 21 },
];

// 从小到大
// arr.sort((a, b) => a - b);
// list.sort((a, b) => a.age - b.age); // 根据数组中对象的某个字段进行排序

// 从大到小
// arr.sort((a, b) => b - a);
// list.sort((a, b) => b.age - a.age);

// 随机
// arr.sort(() => Math.random() - 0.5);
// list.sort(() => Math.random() - 0.5);

// console.log(arr);
// console.log(list);

const dom1 = document.getElementById('ascend');
const dom2 = document.getElementById('descend');
const dom3 = document.getElementById('random');

dom1.addEventListener('click', function () {
    arr.sort((a, b) => a - b);
    list.sort((a, b) => a.age - b.age);

    console.log('升序', arr);
    console.log('升序', list);
});

dom2.addEventListener('click', function () {
    arr.sort((a, b) => b - a);
    list.sort((a, b) => b.age - a.age);

    console.log('降序', arr);
    console.log('降序', list);
});

dom3.addEventListener('click', function () {
    arr.sort(() => Math.random() - 0.5);
    list.sort(() => Math.random() - 0.5);

    console.log('随机', arr);
    console.log('随机', list);
});
<div class="tip">
    <p class="title">数组排序</p>
    <div>
        点击右下角
        <span class="sp">Console</span>
        查看运行结果
    </div>
</div>

<div>
    <button id="ascend">升序</button>
    <button id="descend">降序</button>
    <button id="random">随机</button>
</div>
.tip {
    background-color: rgba(174,220,174,0.25);
    padding: 0.75rem;
    border-left: 0.35rem solid;
    border-radius: 0.25rem;
    margin: 1.5rem 0;
    font-size: 0.9rem;
    border-color: #5cb85c;
}

.title {
    font-size: 18px;
    font-weight: bolder;
    margin-top: 0;
}

.sp {
    background: orange;
}