javascript - Why I get error 'Cannot set property '0' of undefined' -
i not understand why can not create new object
the error: uncaught typeerror: cannot set property '0' of undefined
i got error on line code. this.gameanimals[i] = {};
this = game; gameanimals[0] = 'frog';
so why have error ? many thanks.
var game = { init: function(){ this.property1 = 1; this.property2 = 2; this.property3 = 3; this.property1000 = 1000; }, cons: function(gameanimals){ for(var = 0; < gameanimals.length; i++){ this.gameanimals[i] = {}; } }, }; var gameanimals = ['frog', 'lion', 'cat']; game.cons(gameanimals);
you trying set zero-th element of this.gameanimals
.
however, this.gameanimals
doesn't exist, since game
object doesn't have private member gameanimals
. hence it's undefined
, try set property on.
i think may mean gameanimals
, without prefixing this
. (alternatively, you'll need create this.gameanimals
first if that's meant.)