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>Todo el código funciona bien, pero el navegador arroja esto:
*
TypeError no detectado: button_dataN[i] no está definido 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
Reemplazar
for (let i = 0; i < widthN * heightN; i++) { for (let j = 0; j < widthN; j++) {con
for (let i = 0; i < heightN; i++) { // Each "rows" for (let j = 0; j < widthN; j++) { // Each "columns" Esas variables i y j son índices de bucle ... Hay un bucle para pasar por las "filas" y otro para pasar por las "columnas" de lo que parece interpretar como una hoja de cálculo.
Con su código, estaba recorriendo filas de 0 a 19 en lugar de 0 a 4.
Entonces, el error ocurrió cuando el script intentó button_dataN[5][0] .
Por favor considere este código
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>