我有这些存储在数组中的对象:
var current = [{1:{X:"",Y:""},2:{X:"",Y:""},3:{X:"",Y:""}},
{1:{X:"",Y:""},2:{X:"",Y:""},3:{X:"",Y:""}},
{1:{X:"",Y:""},2:{X:"",Y:""},3:{X:"",Y:""}}
];
我想要的是动态存储它们并在函数中传递对象值后动态访问它们。
function getXAxis(num){
//any
}
function getYAxis(num){
//any
}
trial1a.X = getXAxis(current[0][1].X);
trial1a.Y = getYAxis(current[0][1].Y);
trial2a.X = getXAxis(current[0][2].X);
trial2a.Y = getYAxis(current[0][2].Y);
trial3a.X = getXAxis(current[0][3].X);
trial3a.Y = getYAxis(current[0][3].Y);
trial1b.X = getXAxis(current[1][1].X);
trial1b.Y = getYAxis(current[1][1].Y);
访问current
值并以动态方式存储它们的最佳方法是什么
答案 0 :(得分:1)
我认为您想要的是动态生成trials
吗?
这样的事情应该做你想做的事情:
var trials = [];
for (var i = 0; i < current.length; i++) {
trials[i] = {};
for (var j in current[i]) {
trials[i][j] = {
X: getXAxis(current[i][j].X),
Y: getYAxis(current[i][j].Y)
};
}
}
答案 1 :(得分:0)
我想我知道你在找什么..
var root = {};
function setValueInDeepStructure(value, path, tree) {
var thisStep = path.shift();
if (path.length == 0) {
tree[thisStep] = value;
} else {
if (!tree[thisStep]) {
tree[thisStep] = {};
}
setValueInDeepStructure(value, path, tree[thisStep]);
}
}
function getValueFromDeepStructure(path, tree) {
var thisStep = path.shift();
if (path.length == 0)
return tree[thisStep];
else
return getValueFromDeepStructure(path, tree[thisStep]);
}
setValueInDeepStructure({x: 3, y: 5}, [0,1,5,6], root);
setValueInDeepStructure(7, [0,1,5,6,'x'], root);
getValueFromDeepStructure([0,1,5,6], root) // => {x:7, y:5}