函数外的数组会被分配空间,但是函数外的变量不会在javascript中分配

array outside a function is allocated space, but a variable outside a function is not allocated in javascript why?

本文关键字:函数 分配 变量 javascript 空间 数组      更新时间:2023-09-26

这是我的javascript代码:

var strp = [0,19,26,33,40,46,49,57,61,65,67,73,76];
var i = document.getElementById("length").value;
function calculator(){
    document.write("the total cost is " + strp[document.getElementById("length").value]);
     document.write("total is ");
     document.write(strp[i]);   
}

我正试图在这里写一个计算函数。HTML部分是这样的:

<form>         
    select size   : <select id="length">
                    <option value="0">Please Choose One...</option>
                    <option value="1">10 inches</option>
                    <option value="2">12 inches</option>
      </select>
    <input type="button" value="Calculate" onclick="calculator()" />
</form>

当我在浏览器中执行此代码时,我通过"getelementbyid值"访问数组,我得到了正确的答案。但是当我将getelmentbyid值存储在变量中,并使用该变量访问数组时,输出是未定义的,为什么会这样?

这是document.write()擦除所有以前的页面内容。请使用适当的DOM操作方法,如innerHTML或appendChild()。

我猜i是未定义的,因为javascript在html之前呈现。所以,当i被创建时,还没有id长度的元素。试着把javascript放到html下面来解决这个问题。