我认为这与Eval有关。
这里,我在运行时有一个未知长度的数组。 比方说,我希望将数组中的值指定为对象的KEYS,如下所示:
var myArr:Array = ['a','b','c',...]; //unknown length
var finalValue:int = 20;
var myObj:Object = new Object();
assignValueToObject();
//logics of assignValueToObject function
/*
//TODO.. black box
*/
//In the end, myObj has the value stored and can be accessed like this
myObj["a"]["b"]["c"][...] = 20;
我不确定我是否需要诉诸eval.hurlant,我希望有一种简单的方法(递归或某种方式)
答案 0 :(得分:2)
只需使用for循环迭代数组的元素并创建除数组的最后一个元素之外的对象,该元素不应该是对象而是所需的值。代码未经测试。
var myArr:Array = ['a','b','c',...]; //unknown length
var finalValue:int = 20;
var myObj:Object = new Object();
// variable that holdsthe msot recently created sub-object
var currentObject = myObj;
// create nested objects up to the second last property name
for (var index:int = 0; index < myArr.length -1; ++i)
{
currentObject = currentObject[element] = {};
}
// add value to last property
currentObject[myArr[myArr.length -1]] = finalValue;
当然,如果要插入许多此类值,则必须检查嵌套对象结构是否已包含某些属性以避免覆盖现有属性。
我不得不说这看起来很复杂,而且你很有可能解决你试图解决的实际问题,而不是将属性名称作为数组中的字符串。
答案 1 :(得分:1)
@null和往常一样,我只是添加了这个例子来实现这个大人物。 你也可以在循环中初始化它,这样你就可以做出你想要的东西(建议你为null)......
var myArray:Array = ["a", "b", "c"];
var mySecondArray:Array = ["a", "b", "c"];
var myValues:Array = ["first element", "secondt element", "third element"];
var relValues:Array = [150, 75, 500];
var indexedValues:Array = [1, 2, 3];
var myObject:Object;
var mySecondObject:Object;
function converArraytToObject(myArray:Array, myValues:Array):Object{
var o:Object=new Object();
for(var i:uint = 0; i < myArray.length; i ++){
o[myArray[i].toString()] = myValues[i].toString();
}
return o;
}
trace(myObject["a"]);
// outputs "first element"
trace(myObject["b"]);
// outputs "second element"
trace(myObject["c"]);
// outputs "third element"
// or
trace(" ***UNSORTED");
for (var j in myObject){
trace ("index name = [" + j + "] = " +myObject[j]);
}
// or
trace(" ***SORTED by index");
for (var k = 0 ; k < myArray.length ; k++){
trace ("index name = [" + myArray[k] + "] = " + myObject[myArray[k]]);
}
//or
trace(" ***UNSORTED");
for (var l in mySecondObject){
trace ("index name = [" + l + "] = " + mySecondObject[l]);
}
//or
trace(" ***SORTED by index");
for (var m = 0 ; m < myArray.length ; m++){
trace ("index name = [" + myArray[m] + "] = " + mySecondObject[myArray[m]]);
}
输出:
如果你想存储Class的相同实例,我建议你使用Vector Class代替Array。
first element
secondt element
third element
***UNSORTED
index name = [c] = third element
index name = [a] = first element
index name = [b] = secondt element
***SORTED by index
index name = [a] = first element
index name = [b] = secondt element
index name = [c] = third element
***UNSORTED
index name = [c] = 3
index name = [a] = 1
index name = [b] = 2
***SORTED by index
index name = [a] = 1
index name = [b] = 2
index name = [c] = 3
ActionScript 3 fundamentals: Arrays
ActionScript 3 fundamentals: Associative arrays, maps, and dictionaries