javascript - 将对象的层次结构作为参数传递给它的父函数

标签 javascript jquery

我在名为 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/

相关文章:

javascript - 使用可调整大小时 div 边框不正确

javascript - 带有 `Please Wait` 标签的 Ajax 组合框用于加载数据

javascript - 使用 JavaScript 进行 Cordova 相机捕获

javascript - 我可以创建不使用 Javascript 的 HTML 弹出窗口吗?或者我可以将 Javascript 放入 <body> 部分吗?

javascript - jquery - 在插入符号位置插入元素

jquery - javascript 将值四舍五入到小数点后两位

jquery - 单击时显示/隐藏 div 使用 jQuery 创建 "click menu"

jquery - 日期在 jquery 中显示不正确

javascript - 让 Jasmine 在服务器端运行

javascript - 在哪里/如何添加自定义 js magento