Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
函数外部的数组被分配了空间,但函数外部的变量在javascript中没有分配为什么?_Javascript_Html_Arrays_Dom_Getelementbyid - Fatal编程技术网

函数外部的数组被分配了空间,但函数外部的变量在javascript中没有分配为什么?

函数外部的数组被分配了空间,但函数外部的变量在javascript中没有分配为什么?,javascript,html,arrays,dom,getelementbyid,Javascript,Html,Arrays,Dom,Getelementbyid,这是我的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.wr

这是我的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>

选择大小:
请选择一个。。。
10英寸
12英寸

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

我猜是
i
是未定义的,因为javascript在html之前呈现。因此,当创建
i
时,还没有id长度的元素。尝试将javascript放在html下面以解决此问题。

这是删除页面上所有以前的内容。请使用一些适当的DOM操作方法,例如或。

Hmm。。。事实上,这个(+1)你是对的,不过当OP解决了这个问题时,我的答案步骤中的那个就改了……但是为什么定义了数组strp,而不是我?它是某种javascript优化
document。如果元素还不存在,getElementById()将返回
未定义的
。因此,
i
是未定义的,因为您正在将
undefined
分配给它。不,这不是优化。当您创建
strp
变量时,它被分配给您创建的数组,即
[0,19,26,33,40,46,49,57,61,65,67,73,76]
。当您创建变量
i
时,您正在将其分配给尚不存在的对象,因此它是未定义的。
strp
变量不依赖于任何html。是的,您是对的。我刚刚尝试了这个,在我通过getelementbyid访问数组的document.write()下面写了另一个document.write()语句,它没有显示任何内容。这是为什么?你在写,我刚刚检查过,document.write()正在清除页面上所有以前的内容。但是为什么会这样呢?@user2437762我已经在中解释过了,尽管我链接的MDN页面也解释过了。