我有以下 JavaScript,我想将其转换为 CoffeeScript:
function initPage() {
var tr = document.getElementsByTagName('tr')[0];
labs.forEach(function(lab) {
var td = document.createElement('td');
// Create a header for each lab.
var h2 = document.createElement('h2');
h2.innerHTML = lab.name;
td.appendChild(h2);
// Create a div for each machine in a given lab.
for(i = lab.first; i <= lab.last; i++) {
var machine = ((i < 10) ? "0" : "") + i;
var div = document.createElement('div');
div.setAttribute('id', lab.name + "-" + machine);
div.setAttribute('class', 'Grey');
div.innerHTML = machine;
td.appendChild(div);
}
// Append the new table data element to the table row.
tr.appendChild(td);
});
}
现在我的 CoffeeScript 翻译看起来像这样:
initPage = () ->
tr = document.getElementsByTagName('tr')[0]
labs.forEach (lab) ->
td = document.createElement 'td'
# Create a header for each lab.
h2 = document.createElement 'h2'
h2.innerHTML = lab.name
tr.appendChild h2
# Create a div for a machine given the machine number
createDiv = (i) ->
machine = if i < 10 then "0#{i}" else "#{i}"
div = document.createElement 'div'
div.setAttribute 'id', "#{lab.name}-#{machine}"
div.setAttribute 'class', 'Grey'
div.innerHTML = machine
td.appendChild div
# Create a div for each machine in a given lab
createDiv machine for machine in [lab.first..lab.last]
# Append the new table data element to the table row.
tr.appendChild td
有没有更好、更惯用的方法来为每个实验室创建 div?避免使用 createDiv 函数并执行以下操作会更好吗:
for i in [lab.first..lab.last]
machine = if i < 10 then "0#{i}" else "#{i}"
div = document.createElement 'div'
div.setAttribute 'id', "#{lab.name}-#{machine}"
div.setAttribute 'class', 'Grey'
div.innerHTML = machine
td.appendChild div
CoffeeScript language reference说
Most of the loops you'll write in CoffeeScript will be comprehensions over arrays, objects, and ranges.
和
Comprehensions should be able to handle most places where you otherwise would use a loop, each/forEach, map, or select/filter
我对列表推导式的想法很陌生,并且希望确保我以适当利用 CoffeeScript 优势的方式翻译此代码。
最佳答案
Would it be better to avoid the createDiv function and just inline it?
是的,这个功能看起来有点多余。
I'm new to the idea of list comprehensions and want to make sure that I'm translating this code in an appropriate way
list comprehensions的目标是构建新的列表,就像 map
和 filter
一样。经常使用 for which 循环或(不恰本地)forEach
,手动推送
到数组。
但是,您的目标不是创建一个数组,而只是创建一个 DOM 元素。推导式在这里没有帮助,您需要将它们用作循环来执行副作用。
关于javascript - 将嵌套 JavaScript 循环重构为 CoffeeScript 推导式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24102142/