使用数组访问多维数组
Accessing multidimensional array with an array
如果以下是我的问题数组,我如何通过在数组中提供索引值来获得位置[0][2][1]
的值,例如:answer = [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(answer)或question.get(answer)这样的方法吗?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));
让我们来找点乐子…
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]));
您可以使用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));
相关文章:
- 将图像数组访问到动态表中
- JavaScript 自包含函数数组访问自我索引
- 如何使用 angularjs 从 json 数组访问数组
- 带逗号的 JavaScript 数组访问
- JavaScript 数组访问问题
- 从 js obj 数组访问外部 js obj 属性
- 如何从数组访问 json 对象
- Javascript-使用索引数组访问数组的元素
- Javascript 全局数组访问成员未定义
- javascript成对值数组访问
- 如何传递到该数组中对象的数组访问属性的排序方法的函数
- 我怎么能给我的属性的默认数组访问传入的jQuery对象在我的插件
- Javascript数组访问不能在IE 7中工作
- 在Mustache.js / ICanHaz中从内部数组访问外部数组值
- Ajax JSON数组——访问信息
- 如何从存储在变量中的数组访问键?
- 通过JSON AJAX数组访问数据->对象
- 使用数组访问多维数组
- Javascript数组访问未定义
- 如何从单击处理程序中的对象数组访问对象属性