使用数组访问多维数组
问题描述:
如果以下是我的数组问题,那么如何通过在数组中提供索引值(例如:answer = [0, 2, 1]
)来获取位置[0][2][1]
中的值。使用数组访问多维数组
var question = [
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
]
];
var answer = [0,2,1];
question.get(answer); // Is there a way like this?
有没有像question.get(回答)方式或question.get([0,2,1])?
答
有一个硬编码方式:
question[answer[0]][answer[1]][answer[2]];
或一个数组或嵌套数组的任何时间长度:
var question = [
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
]
];
var answer = [0,2,1];
var getanswer= function(answerinput,questioninput){
var val = questioninput;
answerinput.forEach(function(item){
val = val[item];
});
return val;
}
console.log(getanswer(answer,question));
+0
动态部分是完美的。我希望有一种方法可以在不运行循环的情况下实现这一点。我没有自己的声望,以upvote。将做未来。谢谢。 –
+0
@OwthamanRooben我认为不循环的唯一方法是硬编码,也相信如果你无法赞成,你可以接受答案。我很高兴这对你有帮助! –
答
你可以使用Array#reduce
,因为你可以使用question
数组作为输入和通过迭代给定的answer
数组获得值。
var question = [[['000', '001', '002'], ['010', '011', '012'], ['020', '021', '022']], [['100', '101', '102'], ['110', '111', '112'], ['120', '121', '122']], [['200', '201', '202'], ['210', '211', '212'], ['220', '221', '222']]],
answer = [0, 2, 1],
getItem = function (array, path) {
return path.reduce(function (a, p) { return a[p]; }, array);
};
console.log(getItem(question, answer));
ES6
var question = [[['000', '001', '002'], ['010', '011', '012'], ['020', '021', '022']], [['100', '101', '102'], ['110', '111', '112'], ['120', '121', '122']], [['200', '201', '202'], ['210', '211', '212'], ['220', '221', '222']]],
answer = [0, 2, 1],
getItem = (array, path) => path.reduce((a, p) => a[p], array);
console.log(getItem(question, answer));
答
让我们有一些乐趣...
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var question = [
[
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9']
],
[
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
],
[
[':', ',', '?'],
['#', '$', '%'],
['+', '!', '&']
]
];
console.log(question.getNestedValue(...[0,2,1]));
console.log(question.getNestedValue(...[1,2,0]));
console.log(question.getNestedValue(...[2,0,1]));
你是指'问题[0] [2] [1]'? – vlaz
不,我认为这意味着从答案中提供确切的数值。我正在寻找一种动态的方法。考虑答案数组是否构建在用户的响应上。 –
我现在看到了。看看@ adeneo的回答,在那种情况下 - 这正是你想要的。 – vlaz