【问题标题】:How to convert a javascript string to reference an object property?如何将 javascript 字符串转换为引用对象属性?
【发布时间】:2015-04-24 22:13:24
【问题描述】:

我有一个带有一堆数组属性的自定义对象。

function Location (name, displayName){
  this.name = name,
  this.displayName = displayName,
  Location.objects.push(this);                           
}
Location.objects = [];

//Initialize Farm
var farm = new Location();

farm.scenes = [
  "content 0",
  "content 1",
  "Content 2"
];

使用 JQuery,我从 DOM 中获取一个属性,我需要使用该属性从对象中调用值。

$('button').click(function(){
      var location = $(this).attr('id'); //in this case, the id is 'farm'
      mainLoop(location);
});

function mainLoop(location){
  console.log(farm.scenes.length);// returns '3' as desired    
  console.log(location.scenes.length);//returns undefined because location is a string. I need this to work.
  console.log(location[scenes][length]); //same problem
}

到目前为止,我发现的唯一解决方案是使用 eval(),但我不能这样做,因为最终用户可能会操纵这些数据。

function mainLoop(location){
  location = eval(location); 
  console.log(location.scenes.length);//returns 3 as desired
}

我需要一种替代方法来获取此字符串并将其转换为对象属性引用。在这种情况下,我处理的结果数量有限,因此我可能会将一组字符串映射到标识符,但我觉得可能有一个更优雅的解决方案,尽管我不知道我应该问什么问题正在输入stackoverflow。

有一个类似的问题Dynamically access object property using variable,但这不适用于此处 - 以下两行使用两种表示法都将解析“3”。我认为我的语法在符号上是正确的,所以我一定是做错了其他事情。

console.log(location.scenes.length);    //returns undefined because location is a string. I need this to work.
console.log(location[scenes][length]);  //same problem

【问题讨论】:

    标签: javascript string object properties eval


    【解决方案1】:

    由于使用location = eval(location); 将其转换为您想要的对象,我假设location 作为传递给您的mainLoop 函数只是表示对象的JSON 字符串,相当于'{"scenes" : ["content 0", "content 1", "Content 2"]}'

    您可以使用JSON.parse - 在这种情况下:

    console.log(location);
    // outputs '{"scenes" : ["content 0", "content 1", "Content 2"]}'
    location = JSON.parse(location);
    console.log(location.scenes.length); // outputs 3
    

    现在,它在浏览器中几乎是标准的。 this related SO question 中有关于 JSON.parse 的更多信息,它指出如果您已经在使用 jquery(看起来就像是这样),那么您可以使用 $.parseJSON,它将通过回退到 @ 来处理较旧的浏览器987654330@.

    【讨论】:

      猜你喜欢
      • 2019-03-20
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多