【问题标题】:array outside a function is allocated space, but a variable outside a function is not allocated in javascript why?函数外的数组被分配了空间,但是在javascript中没有分配函数外的变量,为什么?
【发布时间】:2013-06-02 21:01:34
【问题描述】:

这是我的 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 值存储在一个变量中,并使用该变量访问数组时,输出未定义为什么会这样?

【问题讨论】:

    标签: javascript html arrays dom getelementbyid


    【解决方案1】:

    这是 document.write() 清除页面上所有以前的内容。请改用一些适当的 DOM 操作方法,例如 innerHTMLappendChild()

    【讨论】:

    • 你在写,我刚刚检查过,document.write() 正在清除页面的所有先前内容。但是为什么会这样呢?
    • @user2437762 我已经在my answer here 中进行了解释,尽管在我链接的 MDN 页面上也进行了解释。
    【解决方案2】:

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

    【讨论】:

    • 嗯......实际上你是对的(+1),虽然当 OP 修复这个问题时,我的答案步骤中的那个......
    • 但是为什么定义了数组strp,而没有定义i?是某种 javascript 优化
    • document.getElementById() 返回 undefined 如果该元素尚不存在。所以i 是未定义的,因为您将undefined 分配给它。
    • 不,它不是优化。当您创建strp 变量时,它被分配给您创建的数组,即[0,19,26,33,40,46,49,57,61,65,67,73,76]。当您创建变量i 时,您将它分配给尚不存在的东西,因此它是未定义的。 strp 变量不依赖于任何 html。
    • 是的,你是对的。我刚试过这个,我在 document.write() 下面写了另一个 document.write() 语句,我通过 getelementbyid 访问了数组,它没有显示任何内容。这是为什么呢?
    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多