【发布时间】:2016-05-19 09:41:15
【问题描述】:
这是我的代码:
class ArrayND {
/**
* @param {Array<number>} ranks
*/
constructor (ranks) {
this.coords = {}
this._ranks = ranks
}
/**
* @param {number|string} defaultValue
*/
init (defaultValue) {
// How to init this.coords with defaultValue given this._ranks ?
}
}
我想要达到的目标:
const myArrayND = new ArrayND([3, 2])
myArrayND.init(5)
/*
myArrayND.coords should be :
{
0,0: 5,
0,1: 5,
1,0: 5,
1,1: 5,
2,0: 5,
2,1: 5
}
*/
myArrayND.coords[[2, 1]] // returns 5
我的问题是:如何实现 init() 函数,什么时候可以用任何等级构建 ArrayND?
例子:
const firstArray = new ArrayND([])
firstArray.init(5)
// firstArray.coords contains {}
const secondArray = new ArrayND([5])
secondArray.init('aze')
/* secondArray.coords contains {
0: 'aze',
1: 'aze',
2: 'aze',
3: 'aze',
4: 'aze',
} */
const thirdArray = new ArrayND([2, 3])
thirdArray.init(2)
/* thirdArray.coords contains {
0,0: 2,
0,1: 2,
0,2: 2,
1,0: 2,
1,1: 2,
1,2: 2,
} */
const anotherExample = new ArrayND([1, 2, 3])
anotherExample.init(1)
/* anotherExample.coords contains {
0,0,0: 1,
0,0,1: 1,
0,0,2: 1,
0,1,0: 1,
0,1,1: 1,
0,1,2: 1,
} */
...
我不希望 myObject.coords 包含多维数组,因为我在访问和设置多维数组中的值时遇到了其他问题:请参阅 JS multidimentional array modify value。它工作得很好,但丑陋的开关盒非常令人讨厌。
而不是拥有
multiDimArray = [
[
[1],
[2],
[3]
],
[
[4],
[5],
[6]
]
]
multiDimArray[0][1][2] // returns 6
问题是访问:
function setValue(indexArray, value) {
switch (indexArray.length) {
case 0:
multiDimArray = value
case 1:
multiDimArray[indexArray[0]] = value
case 2:
multiDimArray[indexArray[0]][indexArray[1]] = value
case 3:
multiDimArray[indexArray[0]][indexArray[1]][indexArrat[2]] =value
...
// Very ugly and isn't truly dynamic
}
}
我想要
multiDimArray = {
0,0,0: 1,
0,0,1: 2,
0,0,2: 3,
0,1,0: 4,
0,1,1: 5,
0,1,2: 6,
}
multiDimArray[[0, 1, 2]] // returns 6
这样我就可以使用这样的函数动态访问和设置值:(在数组数组的情况下,这是通过丑陋的开关盒完成的)
function setValue(indexArray, value) {
multiDimArray[indexArray] = value
// much better than before.
}
所以我知道“ArrayND”这个名字可能有点误导,但它实际上不是一个数组,它是一个包含 n 维数组坐标的平面对象。
【问题讨论】:
标签: javascript object matrix initialization coordinates