Home > Software design >  Why does setting the value of an array element cause my script to fail?
Why does setting the value of an array element cause my script to fail?

Time:08-14

This simple bit of JavaScript worked fine until I added the line

bigImgExists[figNum - 1] = true; <!-- this line causes problem -->

It’s obviously causing some sort of wrong time error, but I can’t understand why. https://www.w3schools.com/js/js_array_const.asp shows an example of setting an array element in this way. Here’s the full script:

"use strict";
const bigImgExists = new array(18).fill(false);
function showBigImg(figNum) {
    var tempDiv = document.createElement('div');
    tempDiv.setAttribute("id", "bigImg1");
    tempDiv.style.backgroundColor = "white";
    const figcap = document.getElementById('figcap1');
    figcap.appendChild (tempDiv);
    tempDiv.innerHTML = "I created this";
    bigImgExists[figNum - 1] = true; <!-- this line causes problem -->

document.getElementById('thumb'   figNum).style.display = 'none';
document.getElementById('bigImg'   figNum).style.display = 'block';
}

CodePudding user response:

probably this figNum variable is coming as a string add a plus sign and try it. "bigImgExists[ figNum - 1] = true"

CodePudding user response:

const bigImgExists = new array(18).fill(false);

Should be

const bigImgExists = new Array(18).fill(false);

The Array constructor need to be capitalized.
reference Array()

  • Related