我正在尝试使用map
函数从2D数组中获取元素的行和列索引。
这是我的代码-
function getIndex() {
var values = [['a', 'f', 'k', 'p', 'u'], ['b', 'g', 'l', 'q', 'v'], ['c', 'h', 'm', 'r', 'w'], ['d', 'i', 'n', 's', 'x'], ['e', 'j', 'o', 't', 'y']];
var output = values.map(function (row, rowIndex) {
return row.map(function (col, colIndex) {
if (col == 's') {
return values[rowIndex][colIndex];
}
})
});
console.log(output);
}
这是我最后运行它时得到的输出-
[[null, null, null, null, null], [null, null, null, null, null], [null, null, null, null, null], [null, null, null, s, null], [null, null, null, null, null]]
我不打算使用for
循环,因为对于我正在处理的数据集而言,这不是最佳选择。需要在JavaScript数组中使用map
,reduce
或filter
函数。请帮助!
注意:我只需要行和列Index两者,而不需要实际值。
当遍历行时,请使用.findIndex
,这样,如果回调返回真实值,则可以在外部使用索引。遍历列时,使用indexOf
检查要查找的值是否存在于数组中-如果存在,将其分配给外部变量,将return true
分配给findIndex
:
const rows = [
['a', 'f', 'k', 'p', 'u'],
['b', 'g', 'l', 'q', 'v'],
['c', 'h', 'm', 'r', 'w'],
['d', 'i', 'n', 's', 'x'],
['e', 'j', 'o', 't', 'y']
];
let colIndex = -1;
const rowIndex = rows.findIndex((row) => {
const foundColIndex = row.indexOf('s');
if (foundColIndex !== -1) {
colIndex = foundColIndex;
return true;
}
});
console.log(rowIndex, colIndex);
如果未找到任何内容,则两个值均为-1。
如果您的环境非常古老,不支持ES6功能,那么您可以首先对其进行填充:
您可以尝试这个
const rows = [
['a', 'f', 'k', 'p', 'u'],
['b', 'g', 'l', 'q', 'v'],
['c', 'h', 'm', 'r', 'w'],
['d', 'i', 'n', 's', 'x'],
['e', 'j', 'o', 't', 'y']
];
function getIndexOfK(arr, k) {
for (var i = 0; i < arr.length; i++) {
var index = arr[i].indexOf(k);
if (index > -1) {
return [i, index];
}
}
}
console.log(getIndexOfK(rows, 's'));