Im sure this is another time I’m over complicating things, or just making myself loopy.
With just vanilla javascript, i want to make this code output an array of every rgb color code, (im using 25 instead of 255 just for sanity)
var a = [];
for( var i = 0; i < 25; i++ ) {
for( var j = 0; j < 4; j++ ) {
a.push(i)
console.log('rgb('+a+')');
}
}
the above outputs this 25 times:
rgb(0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6…. so on …25,25,25)
Then i tried this, or something like this, i lost what i had planned to show as example i think lol.
var a = [];
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 25; i++ ) {
a.push(i)
console.log('rgb('+a+')');
}
for( var k = 0; k < 4; k++ ) {
console.log('rgb('+a+')');
}
}
either way.
everything i’ve tried doesn’t do what i want. i’ve tried to create a function too, still kinda lost in it.
ok, so this is another version i created, almost does it again, but not quite right:
var n = [];
for( var i = 0; i < 25; i++ ) {
n.push(i);
}
var a = [];
n.forEach( function() {
for(j = 0; j<3;j++) {
var b = j
}
return a.push(n);
});
console.log(a);
outputs 25 arrays with arrays 0-25;
i know it’s something to do with arrays of arrays. thats the where i fail always, foreach loops and arrays have always been my downfall.
You use three loops:
That produces an array (
rarray) of arrays (eachgarray), each of which in turn contains an array (eachbarray) of objects. Each object has anr,g, andbvalue.Note that as selbie points out, you’ll end up with a total of
256 * 256 * 256 = 16,777,216entries spread across the various arrays. You’ll have256 * 256 = 65,536barrays and256garrays. In all, that’s1 + 256 + (256 * 256) + (256 * 256 * 256) = 16,843,009objects. Since all of these objects (including the arrays) are actually key=value maps, each entry will have a key portion and a value portion, and so just the references to those will be four bytes each. Then there’s the actual key data for the array entries (1-3 characters = 2-6 bytes minimum) and the key data for each of our 16M final objects (which have three keys each,r,b, andg). Plus some other overhead. The details will vary a lot by JavaScript environment, but we’re probably talking no less than (waves hands) 32-64 bytes per entry, for a total in memory of ~538MB-1076MB. Now, that’s not a lot by modern computer standards, but it’s a lot for a web page. 🙂 I used Chrome to do it, and it took ~1GB (did it in about 4 seconds — gotta love Chrome). In contrast, after several minutes and >2GB of RAM use, I gave up on Firefox. I wouldn’t go near this in IE with a barge-pole.Live example (using only
0..4rather than0..255).