簡體   English   中英

以隨機順序顯示一組圖像 JavaScript

[英]display an array of images in random order JavaScript

我想以隨機順序打印一個 javascript 圖像數組,但希望中間那個我希望這個 g.jpg 留在它現在所有的位置都是隨機播放,如何分離或絕對 g.jpg 位置。 我想我需要為 g.jpg 添加一個不同的類名,但我不知道該怎么做。

 <html> <head> <meta charset='utf-8'> <title></title> <style> .ppl{ width: 250px; } </style> </head> <body> <div id="root"></div> <script type="text/javascript"> const images = [ 'images/1.jpg', 'images/2.jpg', 'images/g.jpg', 'images/3.jpg', 'images/4.jpg' ] const root = document.querySelector('#root') const shuffle = ([...array]) => { let currentIndex = array.length let temporaryValue let randomIndex // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex) currentIndex -= 1 // And swap it with the current element. temporaryValue = array[currentIndex] array[currentIndex] = array[randomIndex] array[randomIndex] = temporaryValue } return array } const shuffledImages = shuffle(images) shuffledImages.forEach(src => { const image = document.createElement('img') image.src = src image.alt = src image.classList.add('ppl') image.classList.add('pos') root.appendChild(image) }) </script> </body> </html>

似乎是一個有趣的問題。 是的,你可以這樣做。 我的建議是,隨機播放四個內容,然后附加這些內容。

您可以嘗試以下可擴展的邏輯。 這里唯一的困難是,數組列表應該是一個奇數,包括g.jpg

 // Made two arrays of variable lengths. const a1 = [1, 2, 3, 4].map(a => a + ".jpg"); const a2 = [1, 2, 3, 4, 5, 6, 7, 8].map(a => a + ".jpg"); // Check the arrays: console.log({ a1, a2 }); // Shuffle in Random Order. a1.sort(() => 0.5 - Math.random()); a2.sort(() => 0.5 - Math.random()); // Check the arrays: console.log({ a1, a2 }); // Take the first part and second part. const f1 = a1.slice(0, a1.length / 2); const f2 = a2.slice(0, a2.length / 2); const s1 = a1.slice(a1.length / 2); const s2 = a2.slice(a2.length / 2); console.log({ f1, f2, s1, s2 }); // Now combine everything: const r1 = [...f1, "g.jpg", ...s1]; const r2 = [...f2, "g.jpg", ...s2]; console.log({ r1, r2 });

我已經在代碼中添加了所有注釋。 讓我知道這是否有幫助?

對事物的數組部分進行排序后,根據此呈現 HTML。

您可以排除索引進行洗牌。

 const shuffle = ([...array], keep = []) => { let i = array.length; while (i) { const r = Math.floor(Math.random() * i); i--; if (keep.includes(i) || keep.includes(r)) continue; [array[i], array[r]] = [array[r], array[i]]; } return array; } console.log(...shuffle([1, 2, 3, 4, 5], [2]));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM