问题
My current Project is a little Jquery Game. Every picture in the Array Bildquelle (which I saved in a json) belongs to a number in the Array numbers, but in the same order, so that Bild1 is number 1 etc.
But I want to display they in a random order. Is there a way to sort them on the same random system?
Thank you in advance!
var Bildquelle = [
"../img/Bild1.png",
"../img/Bild2.png",
"../img/Bild3.png",
"../img/Bild4.png",
"../img/Bild5.png",
"../img/Bild6.png",
"../img/Bild7.png",
"../img/Bild8.png",
"../img/Bild9.png",
"../img/Bild10.png"
]
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numbers.sort(function() {
return Math.random() - .5
});
for (var i = 0; i < 10; i++) {
var Karte = $('<img src=' + Bildquelle[i] + ' alt="Bild">').data('number', numbers[i]).attr('id', 'card' + numbers[i]).appendTo('#cardPile')
};
回答1:
Probably the easiest is to just not use numbers
but directly shuffle Bildquelle
instead:
Bildquelle.sort(function() {
return Math.random() - 0.5;
});
Now Bilquelle[0]
might be "../img/Bild9.png"
or one of the others.
If you however want to keep Bildquelle
and numbers
and shuffle numbers you should change numbers
to be zero based (as arrays):
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
You could even directly get Bildquelle's keys:
var numbers = Object.keys(Bildquelle);
Now you can shuffle that, and access the Bildquelle by a certain number:
Bildquelle[ numbers[0] ]
or in your loop as:
Bildquelle[ numbers[i] ]
PS: Bildquelle
should actually be images
or pictures
to follow naming conventions (and if you keep mixing languages it gets harder to read...)
来源:https://stackoverflow.com/questions/51937278/order-two-arrays-based-on-the-same-random-sorting-system