按字符串选择全局变量,包括子属性

时间:2015-09-22 20:31:34

标签: javascript object eval

在javascript中,我想通过它的名字选择某个属性,该名称存储在一个字符串中。我知道window[someString]是要走的路。它适用于someString = "somevariable",但遗憾的是,我的程序也会包含someobject.someproperty等字符串。这不起作用。

所以问题是,给定代码

someString = "one.two.three";
one = {
  two: {
    three: "This is the value that I want to get"
  }
};
// window[someString] does not work.

,如何使用one.two.three使用someString 使用eval的值获取Object.defineProperty(Object.prototype,'clean',{enumerable:false,value:function(){ //FUNCTION CLEAN BODY }}) 的值?

2 个答案:

答案 0 :(得分:1)

使用拆分并制作递归方法

var someString = "one.two.three";
var keys = someString.split('.');

one = {
  two: {
    three: "This is the value that I want to get"
  }
};

function getinnerProperty(object, keys) {
  var key = keys.shift();

  if (keys.length) {
    var nestedObject = object[key];
    return getinnerProperty(nestedObject, keys);
  } else {
    return object[key];
  }
}

console.log(getinnerProperty(window, keys));

答案 1 :(得分:0)

您可以编写一个使用split的函数并迭代遍历对象树:

var someString = "one.two.three";
var one = {
  two: {
    three: "This is the value that I want to get"
  }
};

function getValue(keyStr) {
  var keys = keyStr.split('.');
  var result = global;
  for (var i = 0; i < keys.length; i++) {
    result = result[keys[i]];
  }
  return result != global ? result : undefined;
}

getValue(someString);