簡體   English   中英

我做什么都無法訪問函數外部的數組

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

這是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

我包含window.onload,以便我們可以假設input和button不為null

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 = function alerted (){
    myArray.unshift(input.value); // get the value
    return myArray;
};

將命名函數表達式分配給按鈕的單擊處理程序。 該功能應該只從函數中驚動了名是availble的。 不幸的是, IE在這方面被破壞了 (實際上是jScript被破壞了),並使其可作為全局變量使用。

您可能應該使用函數表達式:

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

button.onclick = alerted;

僅在單擊按鈕時,成員才會添加到數組中,然后該成員將為空。 最初,輸入沒有值,因此單擊按鈕(或調用函數)將僅添加空字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM