无论我做什么,都无法访问函数外的数组

时间:2013-11-29 02:53:07

标签: javascript arrays

这是html部分:

<form>
<input id="input" type="text"/>
<button id="button"> Add! </button>
</form>
<div class="list"></div>

脚本是这样的:

var input = document.getElementById("input"); // save the object
var button = document.getElementById("button");

var myArray = [];



button.onclick = function alerted (){
    myArray.unshift(input.value); // get the value
    return myArray;


};

alerted();
document.write(myArray);

问题是无论我做什么,myArray总是保持原始的空数组。我想要开悟,谢谢!

3 个答案:

答案 0 :(得分:1)

您必须使用您为该函数指定的变量的名称,在这种情况下button.onclick()将执行此操作。命名函数表达式允许您在正文中使用名称​​ ,但您必须使用引用名称而不是函数名称来将其调用到其他位置。

button.onclick = function alerted() {
    myArray.unshift(input.value); // get the value
    return myArray;
};

button.onclick();

以这种方式思考 - 您将函数对象分配给变量 - 该函数对象可能有也可能没有名称(匿名)。因此,如果您的函数有一个名称,您可以这样显示它:

button.onclick.name //=> alerted

答案 1 :(得分:0)

我包含window.onload,以便我们可以假设输入和按钮不为空

window.onload = function(){
 var input = document.getElementById("input"); // save the object
 var button = document.getElementById("button");

 var myArray = ["hello"];



 button.onclick = function(){
    myArray.unshift(input.value); // get the value
    document.write(myArray);
 };

}

答案 2 :(得分:0)

以下内容:

button.onclick = function alerted (){
    myArray.unshift(input.value); // get the value
    return myArray;
};

将指定的函数表达式分配给按钮的单击处理程序。 功能只能通过函数中的 alert 名称使用。不幸的是IE is broken(实际上jScript已被打破)并且可以作为全局变量使用。

您应该使用函数表达式:

function alerted (){
    myArray.unshift(input.value); // get the value
    return myArray;
}

button.onclick = alerted;

成员只会在单击按钮时添加到数组中,然后才会为空。最初输入没有值,因此单击按钮(或调用函数)将只添加空字符串。

相关问题