以英文字母(ABCD)排序,新增对象按顺序插入对应索引位置
function insertSorted(array, item) {
// 找到应该插入的位置
const index = array.findIndex(element => element > item);
// 如果没有找到比item大的元素,说明item应该插入在数组末尾
if (index === -1) {
array.push(item);
} else {
// 在找到的位置插入item
array.splice(index, 0, item);
}
}
let array = ['A', 'B', 'C', 'F', 'W'];
// 插入 'K'
insertSorted(array, 'K');
console.log(array); // 输出: ['A', 'B', 'C', 'F', 'K', 'W']