为何设置数组元素值会导致JavaScript脚本运行失败?
问题分析与解决
核心错误:数组构造函数拼写错误
你的代码里new array(18).fill(false)是错误写法——JavaScript的数组构造函数首字母必须大写,正确写法是new Array(18).fill(false)。小写的array是未定义标识符,会直接引发运行时错误,导致后续对bigImgExists的赋值操作失败。关于const数组的误区
你参考的示例里用const声明数组后修改元素是完全可行的:const仅禁止重新赋值整个数组(比如bigImgExists = []这类操作会报错),但允许修改数组内部的元素值。你的问题和const本身无关,纯粹是数组初始化时的拼写失误。修复后的完整代码
"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; document.getElementById('thumb' + figNum).style.display = 'none'; document.getElementById('bigImg' + figNum).style.display = 'block'; }
内容的提问来源于stack exchange,提问作者Hobbyist
相关产品推荐
相关产品推荐

