2016-09-26 22 views
1

我收到提示:這種訪問變量返回地圖不確定

Uncaught TypeError: Cannot read property '1' of undefined 

運行時,以下幾點:

function Polygon(width, height) { 
    this.width = width; 
    this.height = height; 
    this.a = [1, 2, 3, 4, 5]; 

    this.build = function() { 
    this.a.map(function(i, v) { 
     console.log(this.a[v]) 
    }); 
    } 
} 

var square = new Polygon(300, 300); 
square.build(); 

發生這僅當試圖陣列功能,例如內引用this.a變量如Array.prototype.mapreduce。該代碼,但是,存儲工作時局部變量中的變量,像這樣:

function Polygon(width, height) { 
    this.width = width; 
    this.height = height; 
    this.a = [1, 2, 3, 4, 5]; 

    this.build = function() { 
    var b = this.a; 
    b.map(function(i, v){ 
     console.log(b[v]) 
    }); 
    } 
} 

var square = new Polygon(300,300); 
square.build(); 

我的問題是:

  • 爲什麼會出現這個錯誤?
  • 有沒有更好的方法來訪問'類'變量?
  • 這可能是一個JavaScript範圍的錯誤?
+0

我想你的地圖函數回調參數沒有正確匹配。您正在使用當前索引位置的當前值。 – Redu

+0

沒有'this.b'定義... – epascarello

+0

和'我'沒有意義,因爲它不是索引,它是價值。 – epascarello

回答

5

MDN documentationArray.prototype.map

If a thisArg parameter is provided to map, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. (Emphasis added)

這意味着thismap功能是不確定的,所以你要嘗試在undefined用括號標記。這產生TypeError,這表示您正嘗試訪問undefined的屬性。


您還錯誤地使用了ii是實際的元素或項目,而不是索引。您可以只需登錄i,不要下標a

function Polygon(width, height){ 
 
    this.width = width; 
 
    this.height = height; 
 
    this.a = [1, 2, 3, 4, 5]; 
 

 
    this.build = function(){ 
 
    this.a.map(function(i, v){ 
 
     console.log(i); 
 
    }, this); 
 
    } 
 
} 
 

 
var square = new Polygon(300, 300); 
 
square.build();

這將通過可選thisArg作爲Polygon的背景下,正確地記錄。該論點明確指出this上下文,允許訪問this.a

+0

謝謝!沒有注意到..'this'的上下文被切換,如果沒有指定的話。 – KpTheConstructor

+0

@KpTheConstructor'this'正在被明確地傳遞。通過的'this'在'Polygon'的上下文中,並且允許你訪問'this.a'。如果不通過它,你會嘗試在'map'中訪問'this',默認情況下它是'undefined'。 – Li357