我在JavaScript中创建了一个多维数组,我想找到特定值的确切索引。该值将由用户输入。
var array = [];
var k = 0;
for (var i = 0; i < 10; i++) {
array[i] = [];
for (var j = 0; j < 100; j++) {
k = k + 1
array[i].push(k);
}
}
var index = array.indexOf(`**"What to insert here???"**`);
JSFiddle
/**
* Index of Multidimensional Array
* @param arr {!Array} - the input array
* @param k {object} - the value to search
* @return {Array}
*/
function getIndexOfK(arr, k) {
for (var i = 0; i < arr.length; i++) {
var index = arr[i].indexOf(k);
if (index > -1) {
return [i, index];
}
}
}
// Generate Sample Data
var k = 0;
var array = [];
for (var i = 0; i < 10; i++) {
array[i] = [];
for (var j = 0; j < 100; j++) {
k = k + 1;
array[i].push(k);
}
}
var needle = 130;
var result = getIndexOfK(array, needle);
console.log('The value #' + needle + ' is located at array[' + result[0] + '][' + result[1] + '].');
这个例子似乎也适用于不规则的多维数组:
function findIndex(valueToSearch, theArray, currentIndex) {
if (currentIndex == undefined) currentIndex = '';
if(Array.isArray(theArray)) {
for (var i = 0; i < theArray.length; i++) {
if(Array.isArray(theArray[i])) {
newIndex = findIndex(valueToSearch, theArray[i], currentIndex + i + ',');
if (newIndex) return newIndex;
} else if (theArray[i] == valueToSearch) {
return currentIndex + i;
}
}
} else if (theArray == valueToSearch) {
return currentIndex + i;
}
return false;
}
var a = new Array();
a[0] = new Array(1, 2, 3, 4, 5);
a[1] = 'ciao';
a[2] = new Array(new Array(6,7),new Array(8,9),10);
var specificIndex = findIndex('10', a);
我写得很快,所以每个人都被邀请来改进这个函数!
注。现在该函数返回一个STRING值,所有索引用逗号分隔,您可以简单地编辑它以返回一个对象
On
function indexOf2d(arr, val) {
var index = [-1, -1];
if (!Array.isArray(arr)) {
return index;
}
arr.some(function (sub, posX) {
if (!Array.isArray(sub)) {
return false;
}
var posY = sub.indexOf(val);
if (posY !== -1) {
index[0] = posX;
index[1] = posY;
return true;
}
return false;
});
return index;
}
console.log(indexOf2d(array, 50));
我的代码就像MS Excel中的PROCV…并标识仅在第一列中搜索的索引。也许可以帮助你(或其他人)。
var convertToRoman = function (valueLimitTen) {
var convertTable = [ [1, "I"],
[2, "II"],
[3, "III"],
[4, "IV"],
[5, "V"],
[6, "VI"],
[7, "VII"],
[8, "VIII"],
[9, "IV"],
[10, "X"],
];
var myIndex;
for(var i in convertTable){
if(convertTable[i][0] == valueLimitTen){
myIndex = i;
return convertTable[i][1];
}
}
}
console.log(convertToRoman(2)); //Result II
console.log(convertToRoman(10)); //Result X
ES6使这变得相当容易。
function findIndexOfNestedArray(nestedArray, searchArray) {
return searchArray.findIndex(item => {
return item.length === nestedArray.length
&& item.every((a, i) => a === nestedArray[i])
})
}
有一个非常简单的方法:
[1,2] === [1,2] // > false
JSON.stringify([1,2]) === JSON.stringify([1,2]) // > true
所以我们可以这样做:
arrays.findIndex(array => JSON.stringify(array) === JSON.stringify(arrayToCompare))
使用findIndex()和indexOf(),您可以在两行中完成:
const valueToSearch = "whatever";
let row = yourArray.findIndex((elem)=>elem.includes(valueToSearch));
let column = yourArray[row].indexOf(valueToSearch);