document.addEventListener("DOMContentLoaded", () => {
const keypad = document.querySelector("#keypad");
const widthN = 4;
const heightN = 5;
const keysN = [];
const widthA = 7;
const heightA = 5;
const keysA = [];
let button_dataN = [
[ "C", "()", "%", "/" ],
[ "7", "8", "9", "*" ],
[ "4", "5", "6", "-" ],
[ "1", "2", "3", "+" ],
["+/-", "0", ".", "=" ]
];
createKeypadN()
function createKeypadN() {
keyPadBody = document.createElement("div");
keyPadBody.setAttribute("id", "keyPadBody")
keypad.appendChild(keyPadBody);
for (let i = 0; i < widthN * heightN; i++) {
for (let j = 0; j < widthN; j++) {
const key = document.createElement("button");
key.innerHTML = button_dataN[i][j];
key.setAttribute("id", button_dataN[i][j]);
keyPadBody.appendChild(key);
keyPadBody.style.height = "250px";
keyPadBody.style.width = "200px";
key.style.height = "50px";
key.style.width = "50px";
keysN.push(key);
}
}
}
})
<div id="keypad"></div>
The whole code works fine but the browser throws this:
*
Uncaught TypeError: button_dataN[i] is undefined createKeypadN file:///home/path/to/calculator/main.js:38 file:///home/path/to/calculator/main.js:95 EventListener.handleEvent* file:///home/path/to/calculator/main.js:1
Replace
for (let i = 0; i < widthN * heightN; i++) {
for (let j = 0; j < widthN; j++) {
with
for (let i = 0; i < heightN; i++) { // Each "rows"
for (let j = 0; j < widthN; j++) { // Each "columns"
Those i and j variable are loop indexes... There is one loop to go through the "rows" and one to go throught the "columns" of what you seem to interpret like a speadsheet.
With your code, you were looping rows from 0 to 19 intead of 0 to 4.
So the error occured when the script tried button_dataN[5][0].
Please consider this code
document.addEventListener('DOMContentLoaded', ()=>
{
const
keypad = document.querySelector('#keypad')
, keysN = []
, button_dataN =
[ [ 'C', '()', '%', '/' ]
, [ '7', '8', '9', '*' ]
, [ '4', '5', '6', '-' ]
, [ '1', '2', '3', '+' ]
, [ '+/-', '0', '.', '=' ]
];
keyPadBody = keypad.appendChild(document.createElement('div'))
keyPadBody.id = 'keyPadBody';
for (let keyVal of button_dataN.flat())
{
let key = keyPadBody.appendChild( document.createElement('button'))
key.textContent = key.id = keyVal;
keysN.push(key);
}
})
#keyPadBody {
height: 250px;
width : 200px;
}
#keyPadBody button {
height: 50px;
width : 50px;
}
<div id="keypad"></div>