Ten sam model jako kod HTML
Praktyka: kalendarz - JavaScript od podstaw: konsola (JavaScript)
Drugi widok tego samego modelu: funkcja `renderHtml` składa napis z kodem tabeli HTML. `<tr>` to wiersz, `<th>` komórka nagłówka, `<td>` zwykła komórka. Model (`buildWeeks`) się nie zmienił, doszedł tylko nowy sposób wyświetlania. W konsoli widzimy kod, a w następnym przykładzie ten sam kod trafi na stronę.
function buildWeeks(year, month) {
const first = (new Date(year, month - 1, 1).getDay() + 6) % 7;
const days = new Date(year, month, 0).getDate();
const cells = [];
for (let i = 0; i < first; i++) cells.push(null);
for (let d = 1; d <= days; d++) cells.push(d);
while (cells.length % 7 !== 0) cells.push(null);
const weeks = [];
for (let i = 0; i < cells.length; i += 7) {
weeks.push(cells.slice(i, i + 7));
}
return weeks;
}
function renderHtml(weeks) {
let html = '<table>\n';
html += '<tr><th>Pn</th><th>Wt</th><th>Śr</th><th>Cz</th><th>Pt</th><th>So</th><th>Nd</th></tr>\n';
for (const week of weeks) {
const cells = week.map(day => `<td>${day === null ? '' : day}</td>`);
html += '<tr>' + cells.join('') + '</tr>\n';
}
return html + '</table>';
}
console.log(renderHtml(buildWeeks(2026, 11)));Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu JavaScript od podstaw: konsola·Zaloguj się, aby zapisać postęp na koncie.