是否可以在不使用Google工作表(电子表格)来保存数据的情况下添加到未知大小的多维数组?无处不在,无法找到三维数组的示例。
这是我想要做的:
var aDirTree=[];
aDirTree[0][0][0]="myName1";
aDirTree[0][0][1]="myURL1";
aDirTree[1][0][0]="myName2";
aDirTree[1][0][1]="myURL2";
//Notice we are skipping elements
aDirTree[2][5][0]="myName3";
aDirTree[2][5][1]="myURL3";
跳过的值是否为空?我猜这可能是某种推送方法。
答案 0 :(得分:2)
在lazier版本中,数组可以用作键(但它被转换为字符串):
var o = {}
o[[1,2,3]]='a'
o['4,5,6']='b'
console.log(o) // { "1,2,3": "a", "4,5,6": "b" }
console.log(o[[0,0,0]]) // undefined

Proxy
(not available in IE)
可以是另一种选择,但它会产生许多额外的价值:
var handler = { get: (a, i) => i in a ? a[i] : a[i] = new Proxy([], handler) }
var a = new Proxy([], handler)
a[1][2][3]='a'
a[4][5][6]='b'
console.log(a) // [[],[[],[],[[],[],[],"a"]],[],[],[[],[],[],[],[],[[],[],[],[],[],[],"b"]]]
console.log(a[0][0][0]) // []

最后,"真实"回答:
function set(a, x, y, z, v) { ((a = a[x] || (a[x] = []))[y] || (a[y] = []))[z] = v }
function get(a, x, y, z, v) { return (a = a[x]) && (a = a[y]) && z in a ? a[z] : v }
var a = []
set(a,1,2,3,'a')
set(a,4,5,6,'b')
console.log( get(a,0,0,0) ) // undefined
console.log( get(a,0,0,0,'default') ) // "default"
console.log( a ) // [,[,,[,,,"a"]],,,[,,,,,[,,,,,,"b"]]]

奖金:所有3种的组合,但效率不高,因为密钥会转换为字符串:
var a = [], p = new Proxy(a, { set: (a, k, v) =>
([x,y,z] = k.split(','), ((a = a[x] || (a[x] = []))[y] || (a[y] = []))[z] = v) })
p[[1,2,3]] = 'a'
p[[4,5,6]] = 'b'
console.log( a[[0,0,0]] ) // undefined
console.log( a ) // [,[,,[,,,"a"]],,,[,,,,,[,,,,,,"b"]]]

答案 1 :(得分:1)
function writeToTree(tree, first, second, third, value)
{
tree[first] || (tree[first] = []);
tree[first][second] || (tree[first][second] = []);
tree[first][second][third] || (tree[first][second][third] = []);
tree[first][second][third] = value;
}
var aDirTree = [];
writeToTree(aDirTree, 1, 55, 3, "someValue");
或者递归地给你任意深度:
function writeToTree(tree, position, value)
{
var insertAt = position.shift();
tree[insertAt] || (tree[insertAt] = []);
if (position.length === 0)
{
tree[insertAt] = value;
return;
}
writeToTree(tree[insertAt], position, value);
}
var aDirTree = [];
writeToTree(aDirTree, [1, 55, 3], "someValue");
console.log(aDirTree);