尝试从计算创build数组时无效的数组长度
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) } } };
这段代码给了我RangeError:无效的数组长度。
但是,当没有计算,像这样:
data: new Array(this.mapSize),
有用。
你能解释一下为什么会这样吗?
为什么会这样呢?
因为map
对象在您尝试读取其mapSize
属性时尚未构build。 所以this.mapSize
给你undefined
。 结果undefined * unedefined
产生NaN
。 数组不能用NaN
长度创build。 尝试只是new Array(NaN)
,你会看到相同的错误。