javascript - Getting TypeError: Cannot set property '0' of undefined when trying to add to array -



javascript - Getting TypeError: Cannot set property '0' of undefined when trying to add to array -

i'm trying larn typescript. in attempt, trying array of numbers, webservice have created, javascript array.

i have next typescript class:

class gamemap2 { grid: uint8array; width: number; height: number; constructor(height: number, width: number) { this.height = height; this.width = width; this.grid = new uint8array(height * width); } generatemap() { alert("calling generate"); $.ajax({ url: "/api/maps/" + this.width + "/" + this.height, async: false, datatype: 'json', success: function(data) { alert("ajax success"); (var idx = 0; idx < data.length; idx++) { this.grid[idx] = data[idx]; } } }); } }

from webservice, like: [1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,1,1,1,1,0,1,0,1,1,1,0,0,0,1,0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,1,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1] now, when seek loop through result, , set grid array, error: typeerror: cannot set property '0' of undefined

if alter this.grid.push(data[idx]); undefined errors. seems me, grid array not within reach of ajax callback. can true, or doing wrong here? there way can array javascript array?

well in fact, issue solved straight typescript. feature called arrow function , alter code defintion this

class gamemap2 { ... constructor(height: number, width: number) { ... } generatemap() { alert("calling generate"); $.ajax({ // instead of // success: function(data) { // utilize style, , compiler magic // of keeping right "this" success: (data) => { alert("ajax success"); (var idx = 0; idx < data.length; idx++) { this.grid[idx] = data[idx]; } } ....

see typescript arrow function tutorial (small cite)

... “arrow function expressions compact form of function expressions omit function keyword , have lexical scoping of this.” arrow function helps retain scope automatically. if @ outputted code compiler, creates var _this = this; , used within function.

javascript json web-services asp.net-web-api typescript

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -