多个嵌套对象的eval()替代方法 [英] Alternatives to eval() for multiple nested objects

查看:83
本文介绍了多个嵌套对象的eval()替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我正在使用的HTML应用程序创建一个通用的i18n解决方案。我正在寻找使用eval()来调用深层嵌套Javascript对象的替代方案:

I'm trying to create a generic i18n solution for a HTML app I'm working in. I'm looking for alternatives to use eval() to call deeply nested Javascript objects:

假设以下HTML示例:

Suppose the following HTML example:

<div id="page1">
  <h1 data-i18n="html.pageOne.pageTitle"></h1>
</div>

和它的伴侣Javascript(使用jQuery):

and it's companion Javascript (using jQuery):

var i18n;

i18n = {
  html: {
     pageOne: {
       pageTitle: 'Lorem Ipsum!'
     }
  }
};

$(document).ready(function () {
  $('[data-18n]').each(function () {
    var q;

    q = eval('i18n.' + $(this).attr('data-i18n'));
    if (q) {
      $(this).text(q);
    }
  });
});

有关如何在不使用eval()的情况下访问i18n对象中的pageTitle属性的任何建议?我需要保留对象的结构,因此将其布局更改为平面解决方案是不可行的。

Any advices on how to access the "pageTitle" property inside the i18n object without using eval()? I need to keep the object's structure, so changing its layout to a "flat" solution is not feasible.

谢谢!!!

推荐答案

您可以使用括号语法,正如其他人所暗示的那样。但是,你需要拆分并迭代

You can use bracket syntax, as others have hinted at. But, you'll need to split and iterate at .:

function lookup(obj, path) {
    var keys = path.split('.'),
        result = obj;

    for (var i = 0, l = keys.length; i < l; i++) {
        result = result[keys[i]];

        // exit early if `null` or `undefined`
        if (result == null)
            return result;
    }

    return result;
}

然后:

q = lookup(i18n, $(this).attr('data-i18n'));
if (q) {
  $(this).text(q);
}

这篇关于多个嵌套对象的eval()替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆