Reputation:
var map = {
mapSize: 100, // the size of a side
data: new Array(this.mapSize * this.mapSize),
getIndex: function(x, y) {
return x * this.mapSize + y;
},
getCoords: function(index) {
var x = Math.floor(index/this.mapSize);
return {
x: x,
y: index - (x * this.mapSize)
}
}
};
This code gives me RangeError: Invalid array length.
However when there is no calculation, like this:
data: new Array(this.mapSize),
it works.
Could you explain me why is that happening?
Upvotes: 1
Views: 2881
Reputation: 193271
why is that happening
Because map
object is not yet constructed by the time you are trying to read its mapSize
property. So this.mapSize
gives you undefined
. As the result undefined * unedefined
produces NaN
. And Array can't be created with NaN
length. Try just new Array(NaN)
and you will see the same error.
Upvotes: 1