gpt4 book ai didi

javascript - Svelte 冒泡排序可视化不会更新 dom

转载 作者:行者123 更新时间:2023-12-05 04:39:55 25 4
gpt4 key购买 nike

我想对许多排序算法进行可视化,为了简单起见,我开始使用冒泡排序。我需要在切换项目时更新 dom,但它只会在所有元素排序后更新它。我查了一下,一切都说要使用 tick,但我仍然无法让它工作,这是我的代码:

<script>
import { tick } from 'svelte';
let arr = [];

async function bubbleSort () {
let len = arr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (arr[j] > arr[j + 1]) {
let tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
await tick();
setTimeout(() => { console.log("World!"); }, 2000);
}
}
}
console.log(arr)
}

function shuffle () {
arr = [];
for (let i = 0; i < 100; i++) {
let num = Math.random()*10+1;
arr.push(Math.floor(num));
}
console.log(arr)
}
console.log(bubbleSort(shuffle()))
</script>

<main>
<button on:click={shuffle}>Shuffle</button>
<button on:click={bubbleSort}>Sort</button>
{#each arr as el, i}
<div id={i} style="position: relative;height: {el*100}px;"></div>
{/each}
</main>

<style>
div {
background: #000000;
width: 5px;
display: inline-block;
margin: 0 1px;
}
</style>

如果这很简单,我很抱歉,但作为一个整体,我对 svelte、js 和 web 开发还很陌生。谢谢!

最佳答案

这是固定的脚本:

<script>
let arr = [];

function sleep(time){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time);
});
}

async function bubbleSort () {
let len = arr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (arr[j] > arr[j + 1]) {
let tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
await sleep(1)
}
}
}
console.log(arr)
}

function shuffle () {
arr = [];
for (let i = 0; i < 100; i++) {
let num = Math.random()*10+1;
arr.push(Math.floor(num));
}
console.log(arr)
}
console.log(bubbleSort(shuffle()))
</script>

<main>
<button on:click={shuffle}>Shuffle</button>
<button on:click={bubbleSort}>Sort</button>
{#each arr as el, i}
<div id={i} style="position: relative;height: {el*100}px;"></div>
{/each}
</main>

<style>
div {
background: #000000;
width: 5px;
display: inline-block;
margin: 0 1px;
}
</style>

sleep 函数基于 MDN 文档中关于 promise 的代码:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises

在 Javascript 中 sleep 实际上并不容易,因为它被设计为永不停止运行。

您可能需要研究 promises 和 async - await 的工作原理,以了解其工作原理。

顺便说一句,您的代码确实更新了 DOM,但它在一瞬间就完成了,因为几乎没有延迟。您使用的 tick 方法仅在 DOM 更新基于之前的更改完成之前停止脚本 - 这通常是非常非常短的时间。

关于javascript - Svelte 冒泡排序可视化不会更新 dom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70371537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com