js添加元素,去重,排序
2021-02-08 本文已影响0人
编程小橙子
javascript-illustration.png
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="myBtn">点击</button>
<div id="div"></div>
</body>
</html>
<script>
let array = [1, 2, 3, 4, 5];
document.getElementById("myBtn").addEventListener("click", () => {
let new_array = [];
let result = add(...array);
for (const k of result) {
if (!new_array.includes(k)) {
new_array.push(k);
}
}
return btnClick(new_array);
});
function btnClick(arr) {
let sort_array = arr.reduce((pre, cur) => {
let i = 0;
while (i < arr.length && cur < arr[i]) i++;
pre.splice(i, 0, cur);
return pre;
}, []);
document.getElementById("div").innerHTML = `[${sort_array}]`;
}
function add(...array) {
let arr = [2, 3, 4, 5, ...array];
return arr;
}
</script>