I've read Deleting array elements in JavaScript - delete vs splice (among other things) which has helped, but I am still at a loss as to why the below code works in the way it does.
There are 10 divs with the class "names" on the page. All currently with an opacity of 1 (included for context).
I'm trying to randomly choose 5 of them, and change their background colour to "red". After using splice() I would expect the array to decrease in size by 1 but this does not happen.
See 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();
Any help appreciated.