Math.random and splice to randomly remove array elements


I read Deleting the table elements in JavaScript - delete vs splice (among other things) that helped, but I still do not know why the code below works as it does.
There are 10 divs with the class "names" on the page. All currently with an opacity of 1 (included for context).
I try to randomly choose 5 of them, and change their background color to "red". After using splice () I would expect the array size to decrease by 1 but that does not happen.
See the live example here: http://jsfiddle.net/RussellEveleigh/Fr85B/1/
 var z = document.getElementById("selected"); var r = function () { b = document.getElementsByClassName("names"); c = []; d = []; for (i = 0; i < b.length; i++) { if (window.getComputedStyle(b[i]).opacity == 1) { c.push(b[i]); } } for (i = 0; i < 5; i++) { num = Math.floor(Math.random() * c.length); z.innerHTML += c.length; // would expect "109876" d.push(c[num]); c.splice(num, num); } for (i = 0; i < d.length; i++) { d[i].style.backgroundColor = "red"; } }; r(); 
Read More Articles

0 Comments:

Posting Komentar