我收到提示:這種訪問變量返回地圖不確定
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.map
和reduce
。該代碼,但是,存儲工作時局部變量中的變量,像這樣:
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範圍的錯誤?
我想你的地圖函數回調參數沒有正確匹配。您正在使用當前索引位置的當前值。 – Redu
沒有'this.b'定義... – epascarello
和'我'沒有意義,因爲它不是索引,它是價值。 – epascarello