(Un)通过字符串输入设置嵌套数组值

时间:2012-05-22 06:33:56

标签: javascript arrays function session reference

我有这样的功能:

Session.get = function(key) {
    if (!window["_SESSION"] || typeof key == 'undefined') {
        return window["_SESSION"] || {};
    }

    if (key.indexOf('.') === -1) {
        return window["_SESSION"][key] || {};
    }

    var keyArr = key.split('.'), val = window["_SESSION"];

    for ( var i = 0; i < keyArr.length; i++) {
        if (typeof val[keyArr[i]] === 'undefined') {
            return null;
        }
        val = val[keyArr[i]];
    }

    return val;
}

这个函数允许我在函数外部获得没有临时变量的嵌套值。示例Session.get('var.nestedvar')的返回值为window[_SESSION']['var']['nestedvar']

Bat我怎么能(un)设置这样的变量?尝试delete val;,但没有工作.. javascript参考如何工作?有没有人知道完成类似功能的替代方案?

2 个答案:

答案 0 :(得分:2)

您可以按父母这样删除:

[10:00:00.380] a = {'root': {'home':'~'}}
[10:00:00.385] ({root:{home:"~"}})
--
[10:00:09.625] b = a['root']
[10:00:09.631] ({home:"~"})
--
[10:00:20.569] delete b['home']
[10:00:20.573] true
[10:00:21.684] a
[10:00:21.688] ({root:{}})

答案 1 :(得分:1)

您可以稍微修改现有代码,例如:

Session.delete = function(key) {
    if (!window["_SESSION"] || typeof key == 'undefined') {
        return false;
    }
    if (key.indexOf('.') === -1) {
        if (key) {
            delete key;
            return true;
        }
    }

    var keyArr = key.split('.'), val = window["_SESSION"];

    var keyDepth = keyArr.length;
    for ( var i = 0; i < keyDepth-1; i++) {
        if (typeof val[keyDepth] === 'undefined') {
            return null;
        }
        val = val[keyDepth];
    }
    if (val[keyDepth-1]) {
        delete val[keyDepth-1];
        return true;
    }
    return false;
}