【问题标题】:Javascript string to object reference (without eval() or indexes)Javascript 字符串到对象引用(没有 eval() 或索引)
【发布时间】:2011-04-13 08:56:46
【问题描述】:

我已经看到了很多相关的问题和谷歌搜索结果,但似乎没有一个与我的问题相符。

我得到一个字符串“header.h2”,我想将它连接到“var objects”。 所以我想要objects.header.h2(其中包含更多的哈希数据)。

但是,我不想使用 eval() 或经常建议的 buttons[],原因很明显,buttons[header.h2] 不起作用,我需要 buttons[header][h2]

那么我怎样才能保持对象符号,或者在最坏的情况下,解决我的问题?

【问题讨论】:

    标签: javascript javascript-objects


    【解决方案1】:

    只是一个可能的方法的速写:

    您的数据

    var data = [
        {foo: 1, bar: 2, foobar: [
            'a', 'b', 'c'
        ]},
        {foo: 1, bar: 2, foobar: [
            'd', 'e', 'f'
        ]},
        {foo: 1, bar: 2, foobar: [
            'g', 'h', 'i'
        ]}
    ];
    
    var accessor = '1.foobar.2';
    

    使用辅助函数

    function helper(data, accessor) {
        var keys = accessor.split('.'),
            result = data;
    
        while (keys.length > 0) {
            var key = keys.shift();
            if (typeof result[key] !== 'undefined') {
                result = result[key];
            }
            else {
                result = null;
                break;
            }
        }
    
        return result;
    }
    

    或者让它对所有对象都可用:(我个人不喜欢这样……)

    Object.prototype.access = function (accessor) {
        var keys = accessor.split('.'),
            result = this;
    
        while (keys.length > 0) {
            var key = keys.shift();
            if (typeof result[key] !== 'undefined') {
                result = result[key];
            }
            else {
                result = null;
                break;
            }
        }
    
        return result;
    };
    

    调试输出

    console.log(
        helper(data, accessor), // will return 'f'
        data.access(accessor) // will return 'f'
    ); 
    

    【讨论】:

    • 那么分割点然后遍历它们并将它们设置在多维数组中?看起来不错!
    【解决方案2】:

    我将创建一个“填充”方法,该方法根据给定的点符号字符串创建对象:

    var populate = function(obj, str) {
      var ss=str.split(/\./), len=ss.length, i, o=obj;
      for (i=0; i<len; i++) {
        if (!o[ss[i]]) { o[ss[i]] = {}; }
        o = o[ss[i]];
      }
      return obj;
    };
    
    var objects = populate({}, 'header.h2');
    objects.header.h2; // => Object {}
    populate(objects, 'foo.bar.gah.zip');
    objects.foo.bar.gah.zip; // => Object {}
    

    需要测试,但应该能让您更接近目标。

    【讨论】:

      猜你喜欢
      • 2014-01-21
      • 1970-01-01
      • 2014-03-02
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多