簡體   English   中英

無法將項目添加到數組

[英]Not possible to add item to array

我正在嘗試將項目添加到數組,但似乎無法實現。 如果我不包含“ this.results.push(res)”,結果將顯示在我的html頁面中,但是如果包含它,則什么也不會發生! 你能幫忙嗎?

這是我當前的代碼:

var results = [];

var fun1 = function(str1) {

    var imag = new Image;
    var starttimer = new Date().getTime();


    $(imag).attr('src', str1 + ':8886/').error(function () {
        var endtimer = new Date().getTime();
        res = (endtimer - starttimer);
        this.results.push(res);
        $('#results').html("" + res + "ms");
    });
}

您需要更改:

this.results.push(res);

至:

results.push(res);

之所以必須使用“ results.push(res)”而不是“ this.results.push(res)”,是因為“ this”的上下文已更改,並且不再指向全局上下文(在其下定義結果數組)。 而是指向觸發錯誤事件的圖像元素。 還請注意,“ fun1”的“ this”上下文將取決於調用對象。 如果在全局范圍內調用它,則將定義“ this.results”,否則將未定義(在fun1的范圍內)。 此外,這還取決於是否以“嚴格”或“非嚴格”模式定義功能。

假設您在所有函數中具有三個不同的圖像元素和相同的錯誤事件處理程序,“ this”將在所有函數中都不同。 實際上,在每個函數中,“這”都將與觸發錯誤事件(圖像1,圖像2或圖像3)的DOM元素相對應,就像費利克斯·克林Felix Kling )在評論中所寫的那樣。

另外,我想指出的是,您實際上可以擁有一個有效的錯誤事件處理函數,在此函數中可以使用“ this.results”。 為此,您將必須使用“調用”,“應用”或“綁定”方法來調用錯誤事件處理程序函數,這些方法允許您在函數內部更改此上下文。

你可以說:

// define your onError event handler
var onError = function () {
    var endtimer = new Date().getTime();
    res = (endtimer - starttimer);
    this.results.push(res);
    $('#results').html("" + res + "ms");
};

// now call it this way
$(imag).attr('src', str1 + ':8886/').error(onError.bind(this));

當然,以這種方式使用“ this”,您將無法訪問圖像屬性,因為此上下文已更改(在您的示例中,您沒有使用圖像屬性,因此在這里沒有危害)。

為了更好地理解javascript全局和函數上下文,請閱讀https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this上的更多內容。

希望這可以幫助。

當您包含this.results.push(res); 在您的代碼瀏覽器中,該行停止,並且不再繼續執行后面的字符串。 在該回調函數中未定義this.results (請在瀏覽器的狀態欄中查看異常通知)。 刪除該行時,一切正常,並且$('#results').html("" + res + "ms"); 命令在html中顯示數據。

使用results.push(res); 而不是this.results.push(res); 因為results變量是全局變量,可用於回調函數。

暫無
暫無

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

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