Javascript can';无论我做什么,都不能访问函数外部的数组

Javascript can';无论我做什么,都不能访问函数外部的数组,javascript,arrays,Javascript,Arrays,这是html部分: <form> <input id="input" type="text"/> <button id="button"> Add! </button> </form> <div class="list"></div> 问题是无论我做什么,myArray始终保持原来的空数组。我想开导一下,谢谢 我包括window.onload,这样我们就可以假设输入和按钮不是空的 window.onload =

这是html部分:

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

问题是无论我做什么,myArray始终保持原来的空数组。我想开导一下,谢谢

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

}

您必须使用分配给函数的变量的名称,在本例中,
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;
};
将命名函数表达式指定给按钮的单击处理程序。函数只能通过从函数中发出警报的名称使用。不幸的是(实际上jScript是坏的)在这方面,并使它作为一个全局变量可用

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

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

button.onclick = alerted;

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

请注意,虽然命名函数表达式很有用,但它们是并且不应该被使用。但是document.write(myArray)仍然会得到原始的空数组,不是由表单输入组成的新表单。使用myArray.push(input.value)?谢谢你的回答,但它仍然没有打印出新的阵列,不知道为什么。
function alerted (){
    myArray.unshift(input.value); // get the value
    return myArray;
}

button.onclick = alerted;