Show sourcecode
The following files exists in this folder. Click to view.
public_html/gamla-kurser/webbutv2/övningar/js_array/
js_array_1.html
js_array_2.html
js_array_3.html
js_array_4.html
js_array_5.html
js_array_6.html
js_array_5.html
77 lines ASCII Windows (CRLF)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Array 5</title>
<style>
table {
border-collapse: collapse;
margin: 20px 0;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
</style>
</head>
<body>
<h1>JS Array 5</h1>
<button onclick="generateArray()">Randomize</button>
<div id="arrayContainer"></div>
<script>
function generateArray() {
let array = [];
let rowSums = [];
let colSums = Array(5).fill(0);
let arrayContainer = document.getElementById("arrayContainer");
arrayContainer.innerHTML = "";
// Generate 5x5 array with random numbers and calculate row sums
for (let i = 0; i < 5; i++) {
array[i] = [];
let rowSum = 0;
for (let j = 0; j < 5; j++) {
let randomNum = Math.floor(Math.random() * 100) + 1;
array[i][j] = randomNum;
rowSum += randomNum;
colSums[j] += randomNum;
}
rowSums.push(rowSum);
}
// Create table to display array and sums
let table = document.createElement("table");
let tbody = document.createElement("tbody");
// Add array rows to table
for (let i = 0; i < 5; i++) {
let tr = document.createElement("tr");
for (let j = 0; j < 5; j++) {
let td = document.createElement("td");
td.textContent = array[i][j];
tr.appendChild(td);
}
let rowSumTd = document.createElement("td");
rowSumTd.textContent = rowSums[i];
rowSumTd.style.backgroundColor = "green";
tr.appendChild(rowSumTd);
tbody.appendChild(tr);
}
// Add column sums to table
let tr = document.createElement("tr");
for (let j = 0; j < 5; j++) {
let colSumTd = document.createElement("td");
colSumTd.textContent = colSums[j];
colSumTd.style.backgroundColor = "green";
tr.appendChild(colSumTd);
}
tbody.appendChild(tr);
table.appendChild(tbody);
arrayContainer.appendChild(table);
}
</script>
</body>
</html>