Answer the question
In order to leave comments, you need to log in
How to randomly shuffle the elements of an object?
I display images using v-for
<div v-for="(image,i) in images" class="game__wrapper_item" :key="i" @click="showCard(image, i)">
<img :src="image.path" alt=""/>
</div>
export const imagesData = [
{id: 1, path: require('./img/image1.jpg')},
{id: 2, path: require('./img/image2.jpg')},
{id: 3, path: require('./img/image3.jpg')},
{id: 4, path: require('./img/image4.jpg')},
{id: 5, path: require('./img/image5.jpg')},
{id: 1, path: require('./img/image1.jpg')},
{id: 2, path: require('./img/image2.jpg')},
{id: 3, path: require('./img/image3.jpg')},
{id: 4, path: require('./img/image4.jpg')},
{id: 5, path: require('./img/image5.jpg')},
]
randomItem (items) {
return items[Math.floor(Math.random()*items.length)];
}
Answer the question
In order to leave comments, you need to log in
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; --i) {
const pos = Math.floor(Math.random() * (i + 1));
const t = arr[pos];
arr[pos] = arr[i];
arr[i] = t;
}
return arr;
}
const newArr = shuffle(imagesData.slice()); // новый перемешанный, imagesData не поменялось
const newArr2 = shuffle(imagesData); // перемешали imagesData, присвоили в newArr2
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question