美文网首页
js添加元素,去重,排序

js添加元素,去重,排序

作者: 编程小橙子 | 来源:发表于2021-02-08 18:32 被阅读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>

相关文章

网友评论

      本文标题:js添加元素,去重,排序

      本文链接:https://www.haomeiwen.com/subject/qarfxltx.html