开发者

Make Objects with key names from variables

开发者 https://www.devze.com 2022-12-15 00:49 出处:网络
I would like to make an Object that has key names taken from a variable. Probably this is not clear enough, so let me make an example.

I would like to make an Object that has key names taken from a variable. Probably this is not clear enough, so let me make an example.

I have two variables var str1:String = 'firstKey'; and str2:String = 'secondKey';

How can I make an object that would look like:

var obj:Object = {firstKey: 'some value开发者_如何学JAVA', secondKey: 'some other value'}, note that firstKey and secondKey are values of variables str1 and str2.

Doing obj = {str1: 'some value', str2: 'some other value'} does not yield a result that I would like

Thanx a bunch for answers! Ladislav Klinc


I'm not sure I understood correctly, but this might be what you want:

var str1:String = 'firstKey';
var str2:String = 'secondKey';

var myObj:Object = {}; // shorthand for a new object
myObj[str1] = 'some value';
myObj[str2] = 'some other value';

The strings within brackets are expanded, so really this is what happens:

myObj.firstKey = 'some value';
myObj.secondKey= 'some other value';


As Lex suggested, just split() a String by a delimiter into an Array and use that to populate your object.

e.g.

//get the values as arrays
var keys:Array = String('firstKey,secondKey').split(',');
var values:Array = String('some value,some other value').split(',');
var keysNum:int = keys.length;
//populate the object
var obj:Object = {};
for(var i:int = 0; i < keysNum; i++) 
    obj[keys[i]] = values[i];
//test
for(var k:String in obj)
    trace('key: ' + k + ' value: ' + obj[k]);

HTH


I think you have to use an array for that. So your object has an array (with the key strings as offset). I'm not sure what the AS 3 syntax is for that, but I'm sure that it's possible.

0

精彩评论

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