So this is a syntax question, I have been reading the MDN docs but i can't find a similar example. I got this particular code snippet from here: https://bost.ocks.org/mike/shuffle/ as I was reading on randomizing arrays.
Here is the full function:
function shuffle(array) {
var copy = [], n = array.length, i;
// While there remain elements to shuffle…
while (n) {
// Pick a remaining element…
i = Math.floor(Math.random() * n--);
// And move it to the new array.
copy.push(array.splice(i, 1)[0]);
}
return copy;
}
Now, I have used it and modified it to fit my needs and it worked fine (although the splicing was a nightmare because it kept destroying my original data) but the point here is this line:
copy.push(array.splice(i, 1)[0]);
I hate not understanding something that would seem basic, but what is the [0] doing in this case? If i take it out the whole thing breaks, but im not sure if it;s part of the splice, or the push, or if its an index of the new array or the spliced array. IF anyone can help shed some light on this i would be very grateful!
Let's break down
copy.push(array.splice(i, 1)[0]);
in the order that it is "executed"
array.splice(i, 1);
array.splice(n, m)
removes m
elements starting and index n
and returns these removed elements as an array ... so in this case you get an array of length 1 - let's call it x
substituting x
for array.splice(i, 1)
in the original code, we now have
copy.push(x[0]);
x[0]
is the one and only element removed from array
- which is pushed on to copy
array
to prevent the incoming array from being mutated
function shuffle(array) {
var copy = [], n = array.length, i;
array = array.slice();
// rest of code
}
By the way, you could also have done
copy.push(array.splice(i, 1).pop());
or
copy.push(array.splice(i, 1).shift());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.