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

can't access array outside a function no matter what I do

本文关键字:访问 函数 数组 什么 可以      更新时间:2023-11-29

这是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总是保持原来的空数组。我希望得到启发,谢谢!

您必须使用为函数分配的变量的名称,在这种情况下button.onclick()即可。命名函数表达式允许您在正文中使用名称,但必须使用引用名称,而不是函数名称才能在其他地方调用它。

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

这样想吧——你把一个函数对象分配给一个变量——这个函数对象可能有名字,也可能没有名字(匿名)。因此,如果你的函数有一个名称,你可以这样显示:

button.onclick.name //=> alerted

以下内容:

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

将命名函数表达式指定给按钮的单击处理程序。函数应该只能通过函数内提醒的名称来使用。不幸的是,IE在这方面被破坏了(实际上jScript被破坏了),并使其可以作为全局变量使用。

您可能应该使用一个函数表达式:

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

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

我包含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);
 };
}