我在名为 tpl()
的函数中有一个名为 html
的对象。
html = {
intro: ['intro', 'html'],
common: { header: ['common', 'header', 'html'] },
more:{ header: { link: ['hello', 'world'] } }
};
我试图通过将其层次结构作为参数传递给 tpl()
来访问 html
的值;
我传递一个字符串 common.header
作为参数,以取回内部对象的内容。
[示例]:
var a = tpl('common.header'); // correct, returns 'common header html'
问题是,当我需要定位更深的嵌套对象时:
var b = tpl('more.header.link'); // how can i make this work ?
这是我编写的函数,但我正在尝试使其更动态(使其可以处理更深层次的对象)。
var tpl = function( path ){
if(!path){ return false; }
var that = this;
that.html = {
intro: ['intro', 'html'],
common: { header: ['common', 'header', 'html'] },
more: { header: { link: ['hello', 'world'] } }
};
path = path.split('.');
return (!!path[1] ? that.html[path[0]][path[1]] : that.html[path[0]]).join('');
/*
// Here is where I am stuck
for(var i = 0; i < path.length; i++){
if( path[i][ path[i+1] ] ){}
}
*/
};
最佳答案
如果我正确理解你的问题,保留一个指向当前子结构的指针怎么样?像这样:
for(var tmp = that.html, i = 0; i < path.length; i++){
tmp = tmp[path[i]];
if (!tmp) return false;
}
return tmp;
关于javascript - 将对象的层次结构作为参数传递给它的父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9082333/