点击运行
const map1 = new Map([ ['z', 'three'], ['a', 'one'], ['b', 'two'], ]); // {'z' => 'three', 'a' => 'one', 'b' => 'two'} console.log(map1); // 升序 const sortedAsc = new Map([...map1].sort()); // {'a' => 'one', 'b' => 'two', 'z' => 'three'} console.log(sortedAsc); // 降序 const sortedDesc = new Map([...map1].sort().reverse()); console.log(sortedDesc); // {'z' => 'three', 'b' => 'two', 'a' => 'one'} // 当键是数字时 const map2 = new Map([ [3, 'three'], [1, 'one'], [2, 'two'], ]); // 升序 const sortNumAsc = new Map([...map2].sort((a, b) => a[0] - b[0])); // {1 => 'one', 2 => 'two', 3 => 'three'} console.log(sortNumAsc); // 降序 const sortedNumDesc = new Map([...map2].sort((a, b) => b[0] - a[0])); // {3 => 'three', 2 => 'two', 1 => 'one'} console.log(sortedNumDesc);
运行结果 :
正在执行...