动态访问Javascript中的数组 [英] dynamic access to an array in Javascript
本文介绍了动态访问Javascript中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
也许已经有了解决方案,但我找不到.我尝试动态访问多维数组中的不同插槽,但是面临着不同深度的挑战.基本上看起来像这样:
Maybe there is already a solution, but I can't find it. I try to access different slots in a multi dimensional array dynamical but with the challenge of different depths. Basically, it looks like this:
var source = [];
source['lvl1'] = [];
source['lvl1']['lvl2a'] = [];
source['lvl1']['lvl2a']['lvl3'] = "ping";
source['lvl1']['lvl2b'] = "pong";
如果深度是固定的,我可以这样编写代码:
If the depth is fix, I could write code like this:
var path1 = ["lvl1","lvl2a","lvl3"];
var path2 = ["lvl1","lvl2b"];
console.log(source[path1[0]][path1[1]][path[2]]); // => ping
console.log(source[path2[0]][path2[1]]); // => pong
我的问题是编写适用于两种变体的代码.这将起作用:
My problem is to write a code that works for both variants. This would work:
switch(path.length)
{
case 1:
console.log(source[path[0]]);
break;
case 2:
console.log(source[path[0]][path[1]]);
break;
case 3:
console.log(source[path[0]][path[1]][path[2]]);
break;
}
但这既不高效也不优雅.有没有其他的解决方案,例如与某种循环一起工作?!?
But this is neither efficient nor elegant. Has somebody another solution that works for example with some kind of loop?!?
谢谢托马斯
推荐答案
您可以从路径(经过测试的代码)中获取值:
You can get a value from a path (tested code):
var getValue = function(path, context) {
if ('object' !== typeof context) {
throw new Error('The context must be an object; "' + typeof context + '" given instead.');
}
if ('string' !== typeof path) {
throw new Error('The path must be a string; "' + typeof context + '" given instead.');
}
var fields = path.split('.'),
getValueFromFields = function(fields, context) {
var field = fields.shift();
if (0 === fields.length) {
return context[field];
}
if ('object' !== typeof context[field]) {
throw new Error('The path "' + path + '" has no value.');
}
return getValueFromFields(fields, context[field]);
}
;
return getValueFromFields(fields, context);
}
var source = [];
source['lvl1'] = [];
source['lvl1']['lvl2a'] = [];
source['lvl1']['lvl2a']['lvl3'] = "ping";
source['lvl1']['lvl2b'] = "pong";
console.log(getValue('lvl1.lvl2a.lvl3', source)); // ping
console.log(getValue('lvl1.lvl2b', source)); // pong
这篇关于动态访问Javascript中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文