【问题标题】:bubble sort on div using height of div fails使用 div 的高度对 div 进行冒泡排序失败
【发布时间】:2021-01-31 04:53:44
【问题描述】:

冒泡排序功能不会根据高度对 div 进行排序。 谁能弄清楚这里出了什么问题 如果一开始排序正确,请尝试多次运行代码

冒泡排序中的if语句即使条件为假也会被执行

Here is codepen link to code

排序功能

    function resolveAfterXSeconds(x) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(x);
        }, x * 1000);
      });
    }

    function swap(el1, el2) {
      const style1 = window.getComputedStyle(el1);
      const style2 = window.getComputedStyle(el2);

      const transform1 = style1.getPropertyValue("height");
      const transform2 = style2.getPropertyValue("height");

      el1.style.height = transform2;
      el2.style.height = transform1;
      console.log(`swapped ${transform1} ${transform2}`);
    }

    async function bubble_sort() {
      let arr = document.querySelectorAll(".bar");

      for (let i = 0; i < arr.length - 1; i++) {
        // let i = 0;
        for (let j = 0; j < arr.length - i - 1; j++) {
          arr[j].style.background = "red";
          arr[j + 1].style.background = "red";

          const ht1 = arr[j].style.height;
          const ht2 = arr[j + 1].style.height;
          if (ht1 > ht2) swap(arr[j], arr[j + 1]);
          await resolveAfterXSeconds(0.5);

          arr[j].style.background = "yellow";
          arr[j + 1].style.background = "yellow";
        }
        arr[arr.length - i - 1].style.background = "green";
      }
    }

【问题讨论】:

    标签: javascript html bubble-sort


    【解决方案1】:

    变量ht1ht2 将是字符串对象,其值类似于“12px”。您需要解析出字符串的数字部分,然后使用parseInt() 将其转换为数字。然后进行比较。

    或者,这会起作用(但不推荐)parseInt("12px")parseInt(ht1) &gt; parseInt(ht2)

    【讨论】:

      猜你喜欢
      • 2011-11-24
      • 2019-05-10
      • 2017-09-27
      • 2022-01-25
      • 1970-01-01
      • 2016-04-13
      • 2019-06-14
      • 1970-01-01
      • 2013-10-31
      相关资源
      最近更新 更多