开发者

How would i go about getting a specific object based on the value of a string with javascript?

I have separate javascript files to load custom objects; these objects are designed to extend some default parameters when the main function is read

they each look like

 var str1= { path:'url1:, var1:5};
 var str2= { path:'url2:, var1:3};
 etc...

I have an array of strings(that is generated from loading an rss page) and i want to return the object based on if its name matches t开发者_如何转开发he object name. hardcoding it would kind of defeat the purpose


Take a look at this question. It shows how to reference objects by using strings. The only difference I can see is that rather than starting with the window object, you would start at whatever object defines your current scope (e.g. this).


You can use the square bracket notation to refer to object properties whose key name is held in a variable:

var key = 'path';
var str1 = { path: 'url', var1: 1};
var value = str1[key]; // value == 'url';

You can also do:

var str1 = 'a';
var str2 = 'b';

var key = 'str1';
var value = window[key]; // value == 'a';


var map = {  "string1": { path: "url1", var1:5},
             "string2": { path: "url2", var1:3} };
...
var url = map[yourstring].path;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜