将字符串转换为对象?

时间:2014-01-29 00:39:19

标签: javascript

我通过对象的属性进行枚举。我直接设置对象时工作正常。

我需要使用prompt(类赋值)来允许用户输入对象名。问题是obj以字符串形式返回

如何将提示中的值转换为对象?

function enumObject(){

    var obj;
    var propertyName;


    obj = prompt("Please enter an object name","window.navigator");
    obj = window.navigator;

    if (typeof obj == "object"){
        for (propertyName in obj){
            document.write(propertyName + " : " + obj[propertyName] + "<br>");
        }
    }
    else {
        alert('The object name is undefined.');
    }

    obj = null;
    propertyName = null;

}

enumObject();

3 个答案:

答案 0 :(得分:1)

对象名称......?!?

您是否希望您的用户通知引用对象的全局变量名称? 如果是这样,你可以这样做:

var name = prompt("Enter a global variable name.");
var obj = window[name];

如果您希望用户输入将转换为对象字面值的字符串,您可以执行以下操作:

var objDef = prompt("Enter a string representing an object");
var obj = eval("(function(){return " + objDef + ";})()");

...或

var objDef = prompt("Enter a string representing an object");
var obj = new Function("return " + objDef)();

如果您想访问功能范围内的对象变量但未使用"strict mode",请尝试:

(function(){
  var someObj = { b:123, c: 321 };
  var name = prompt("Enter an object variable name in local scope.");//Here, your user could enter "someObj"
  eval("console.log(" + name + ")");
})();

答案 1 :(得分:0)

我建议:

function enumObject(){

var obj;
var propertyName;


obj = prompt("Please enter an object name","window.navigator");
window[obj] = {};

if (typeof window[obj] == "object"){
    for (propertyName in obj){
        document.write(propertyName + " : " + obj[propertyName] + "<br>");
    }
}
else {
    alert('The object name is undefined.');
}    
}

enumObject();

答案 2 :(得分:0)

  

我需要使用prompt(类赋值)来允许用户输入   对象名称。问题是obj以字符串形式返回

     

如何将提示中的值转换为对象?

你不能因为Objects没有名字。您可以拥有 value 是对象引用的变量或对象属性,但是:

var obj = {};

创建一个名为 obj 的变量,其值是对象的引用。

如果要动态创建变量,可以使用 eval ,但不建议这样做。我们非常警告使用eval来执行用户输入的随机代码,因为他们完全不知道已经存在的变量并且你不希望它们搞乱。

您可以做的是创建一个专门用于添加属性的对象,因为几乎任何字符串值都可以用作属性名称。所以你可以这样做:

function enumObject(){

    // markup and div will be used later
    var markup = '';
    var div;

    // Here's where the property names will be stored
    var obj = {};
    var propertyName = prompt("Please enter an object name", "window.navigator");
    obj[propertyName] = {};


    // This is redundant since an object was just assigned so it will
    // always return true
    if (typeof obj[propertyName] == "object") {

      // Always perform a hasOwnProperty check so you don't get
      // inherited properties, you only want the ones added by the user
      // Also, don't re-used variables, create a new one
      for (var prop in obj) {

        if (obj.hasOwnProperty(prop)) {

          // Don't use document.write after the page has finished loading
          // as it will clear the entire document first before writing
          markup += propertyName + " : " + obj[propertyName] + "<br>";
        }
      }

    // This should never execute since the test should always be true
    } else {
      alert('The object name is undefined.');
    }

    // Write to the document without destroying it
    div = document.createElement('div');
    div.innerHTML = markup;
    document.body.appendChild(div);
}

修改

您可能希望根据用户定义的字符串访问对象属性。在这种情况下,您可以执行以下操作。如果属性访问者的根不是 window ,它只使用 eval ,并且只显示有效标识符的字符串,而不是随机代码:

// Assumes dot notation like window.navigator or foo.bar
function getObjectValueByString(s) {

  var identifier, path = [];

  // Very simple identifier re
  var identifierRe = /^[_$a-z][a-z0-9_$]*$/i;
  s = s.split('.');

  // Loop over parts of s
  for (var i=0, iLen=s.length; i<iLen; i++) {
    identifier = s[i];
    path.push(identifier);

    if (identifierRe.test(identifier)) {

      // Get root of accessor
      if (i == 0) {

        if (identifier == 'window') {
        obj = window;

         // Only use eval on what appear to be valid identifiers
         // not arbitrary code
         } else {
          obj = eval(identifier);
        }

     // If not root, get property value
     } else {
       obj = obj[identifier];
     }

     // Stop if obj isn't an object
     if (typeof obj != 'object') {

        // Message if didn't get to end of accessor
        if (i < iLen - 1) {
          return 'Stopped at ' + path.join('.') + ' = ' + obj;
        }            
      }
    } else {
    return identifier + ' is not a valid identifier';
    }
  }

  return path.join('.') + ' = ' + obj;
}

玩它:

<input onblur="console.log(getObjectValueByString(this.value));">

排除保留字的标识符名称的更严格的正则表达式在Valid Characters for JavaScript Variable Names的接受答案中。

如果只需要 window 的属性,生活变得更加简单,根本不需要eval,因此正则表达式也不能检查有效的标识符:

function getWindowValueByString(s) {

  var identifier, path = [];
  var obj = window;
  s = s.split('.');

  // Loop over parts of s
  for (var i=0, iLen=s.length; i<iLen; i++) {
    identifier = s[i];
    path.push(identifier);

    // Check only using window
    if (i == 0) {
      if (identifier != 'window') {
        return 'Only valid for properties of window';
      }

    } else {
      obj = obj[identifier];
    }

    // Stop if obj isn't an object
    if (typeof obj != 'object') {

      // Message if didn't get to end of accessor
      if (i < iLen - 1) {
        return 'Stopped at ' + path.join('.') + ' = ' + obj;
      }            
    }
  }

  return path.join('.') + ' = ' + obj;
}
相关问题