Визуализировать массив изображений в случайном порядке - PullRequest
0 голосов
/ 05 мая 2020

У меня есть несколько объектов Figure, хранящихся в массиве с именем figureTab, а используемые элементы я храню в массиве с именем used.

Нужно ли мне дважды устанавливать случайное число? Объекты внутри массива

var used = [];
for (let i = 0; i < figureTab.length; i++) {
  var random = Math.floor(Math.random() * figureTab.length);


  if (used.length == 0) {
      used.push(random);
      html += "<div>" + (figureTab[random].FigureNr + 1) + "></div>"
  }
  else{
      for (let j = 0; j < used.length; j++) {
          if (used[j] == random) {
              random = Math.floor(Math.random() * figurTab.length);
              j = 0;
          }
       }    
       used.push(random);
       html += "<div>" + (figureTab[random].FigureNr + 1) + "></div>";
   }


document.getElementById("alternatives").innerHTML = html;

Ответы [ 2 ]

0 голосов
/ 05 мая 2020

Есть две функции:

/*
- Shuffles an array properly -- without duplicates -- based on the Fischer-Yeats 
  algorithm
*/
shuffle(array)

/*
- Passes an htmlString, an array, and an optional selector of the tag that the new
  HTML will be rendered into (if no selector is provided then it will render to 
  <body> by default).
*/
function renderString(string, shuffled, selector = 'body')

function renderString(string, shuffled, selector = 'body') {
  const node = document.querySelector(selector);
  for (let [index, url] of shuffled) {
    node.insertAdjacentHTML('beforeend', string);
    node.lastElementChild.firstElementChild.src += url;
    node.lastElementChild.lastElementChild.textContent = index;
  }
}

function shuffle(array) {
  let qty = array.length,
    temp, i;
  while (qty) {
    i = Math.floor(Math.random() * qty--);
    temp = array[qty];
    array[qty] = array[i];
    array[i] = temp;
  }
  return array;
}

const thumbs = [[0, '/img/link.gif'], [1, '/img/sol.png'], [2, '/img/ren.gif'], [3, '/img/balls.gif'], [4, '/img/austin.gif']];

const htmlString = `
<figure>
  <img src='https://glpjt.s3.amazonaws.com/so/av'>
  <figcaption></figcaption>
</figure>`;
let mixed = shuffle(thumbs);
//console.log(mixed);

renderString(htmlString, mixed, 'main');
main {
  display: flex;
  flex-flow: column nowrap;
  justify-content: start;
  width: 80%;
  margin: 0 auto;
}

figure {
  width: 320px;
  margin: 0 auto;
  padding: 5px 10px;
  outline: 3px outset tomato;
  font-family: Verdana;
  font-size: 3rem;
}

img {
  display: block;
  max-width: 100%;
  height: auto;
  object-fit: contain;
}

figcaption {
  text-align: center;
}
<main></main>
0 голосов
/ 05 мая 2020

Если то, что вам нужно, это тасовка массивов, есть гораздо более короткий способ сделать это (реализация алгоритма Фишера-Йейтса ), используя Array.prototype.reduceRight():

const src = [{id:0, name: 'circle', path:'data:image/svg+xml;base64, PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCiAgPGNpcmNsZSBjeD0iNTAiIGN5PSI1MCIgcj0iNTAiLz4NCjwvc3ZnPg=='}, {id:1, name: 'triangle', path: 'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCsKgIDxwYXRoIGQ9Ik0wLDAgaDEwMCB2MTAwIHoiLz4NCjwvc3ZnPg=='}, {id:2, name: 'rhombus', path:'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCsKgIDxwYXRoIGQ9Ik01MCwwIGw1MCw1MCBsLTUwLDUwIGwtNTAtNTAgeiIvPg0KPC9zdmc+'}, {id:3, name: 'square', path: 'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCsKgIDxwYXRoIGQ9Ik0wLDAgaDEwMCB2MTAwIGgtMTAwIHoiLz4NCjwvc3ZnPg=='}, {id:4, name: 'trapezoid', path:'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCsKgIDxwYXRoIGQ9Ik0wLDEwMCBoMTAwIGwtMjAsLTEwMCBoLTYwIHoiLz4NCjwvc3ZnPg=='}],
      wrapper = document.getElementById('wrapper'),

      shuffle = arr => arr.reduceRight((r,_,__,s) => 
        (r.push(s.splice(0|Math.random()*s.length,1)[0]), r),[])

shuffle(src).forEach(({name,path}) => {
  const figure = document.createElement('img')
  figure.src = path
  figure.alt = name
  wrapper.appendChild(figure)
})
img{
  width: 100px;
  height:100px;
  margin: 10px;
}
<div id="wrapper"></div>
...