我正在尝试在coffeescript 中学习javascript,并通过在codepen 上重写一些简洁的javascript 来练习。出了点问题,我认为这是由于我不知道如何在咖啡脚本中编写嵌套循环。原始代码是:
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);
}
}
我的“翻译”是:
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()
不确定什么不起作用。如果不是这样,我仍然不确定。原笔在:
http://codepen.io/pixelgrid/pen/Hxkhs
我的叉子是:
http://codepen.io/bubbaJackson/pen/tyLGC
谢谢。