Reputation: 61
I'm trying to learn javascript in coffeescript, and am practicing by rewriting some neat javascript on codepen. Something's gone wrong, and I think it'd due to my ignorance of how to write a nested loop in coffee script. The original code is:
for(var j = 0 ; j<yElems;j++){
for(var i = 0 ; i<xElems;i++){
var elem = document.createElement('div');
if(i%2==0){
elem.classList.add('bs');
}else{
elem.classList.add('bs1');
}
elem.style.top = j*30-20+'px';
elem.style.left = i*30-20+'px';
elem.style.zIndex =100- j+''+i;
elem.style.backgroundColor = colors[Math.round(Math.random()*4)];
body.appendChild(elem);
elems.push(elem);
}
}
and my 'translation' is:
grid = ->
for i in xElems
elem = document.createElement 'div'
if i % 2 is 0 then elem.classList.add 'bs' else elem.classList.add 'bs1'
elem.style.top = j*30-20+'px'
elem.style.left = i*30-20+'px'
elem.style.zIndex = 100- j+''+i
elem.style.backgroundColor = colors[Math.round(Math.random()*4)]
body.appendChild(elem)
elems.push(elem)
for j in yElems
grid()
Not sure what's not working. And if it's not that, i'm still not sure. The original pen is at:
http://codepen.io/pixelgrid/pen/Hxkhs
and my fork is:
http://codepen.io/bubbaJackson/pen/tyLGC
Thanks.
Upvotes: 0
Views: 527
Reputation: 25728
for i in xElems
should be
for i in [0..xElems] by 1
The same should be done for the j loop as well.
i in xElems will try to treat xElems as an array and give you each element in the array. xElems appears to be a number in the original js, and so you want to iterate over a range, which you can do by using the [a..b]
notation. Note that [a..b]
will exclude b, while [a...b]
will include the value of b.
As mu is too short
points out in the comments, this compiles directly to basically what you were trying to copy: for(i = 0; i < xElems; ++i)
Upvotes: 2