本文介绍了使用字符串搜索在多维数组中查找坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试在此问题中提供其他选择,不要让步!只需使用indexOf和一些整数数学
Try to give an alternative in this question WITHOUT LOOPING! Just using indexOf and some integer math
下面的代码似乎很有希望,但失败了。
The code below seemed promising but fails.
任何具有较高数学技能的人都想解决它吗?
Anyone with better math skills feel like fixing it?
var letterVariations = [
[' ','0','1','2','3','4','5','6','7','8','9'],
['A','a','B','b','C','c','D','d','E','e',';'],
['Â','â','F','f','G','g','H','h','Ê','ê',':'],
['À','à','I','i','J','j','K','k','È','è','.'],
['L','l','Î','î','M','m','N','n','É','é','?'],
['O','o','Ï','ï','P','p','Q','q','R','r','!'],
['Ô','ô','S','s','T','t','U','u','V','v','"'],
['W','w','X','x','Y','y','Ù','ù','Z','z','"'],
['@','&','#','[','(','/',')',']','+','=','-'],
];
var string = JSON.stringify(letterVariations);
var pos = string.indexOf("u")
console.log(Math.floor((pos/10)%8),pos%10)
// fails, how to fix?
pos = string.indexOf("M")
console.log(Math.floor((pos/10)%8),pos%10)
推荐答案
function findPos(array, symbol) {
const string = array.toString().replace(/,/g, '');
const pos = string.indexOf(symbol)
const d = (array[0] || []).length
const x = pos % d;
const y = Math.floor(pos / d)
return { x, y }
}
const array = [
[' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', ';'],
['Â', 'â', 'F', 'f', 'G', 'g', 'H', 'h', 'Ê', 'ê', ':'],
['À', 'à', 'I', 'i', 'J', 'j', 'K', 'k', 'È', 'è', '.'],
['L', 'l', 'Î', 'î', 'M', 'm', 'N', 'n', 'É', 'é', '?'],
['O', 'o', 'Ï', 'ï', 'P', 'p', 'Q', 'q', 'R', 'r', '!'],
['Ô', 'ô', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', '"'],
['W', 'w', 'X', 'x', 'Y', 'y', 'Ù', 'ù', 'Z', 'z', '"'],
['@', '&', '#', '[', '(', '/', ')', ']', '+', '=', '-'],
];
console.log(findPos(array,' ')) //=> [0, 0]
console.log(findPos(array,'M')) //=> [4, 4]
console.log(findPos(array,'u')) //=> [6, 7]
console.log(findPos(array,'-')) //=> [8, 10]
这篇关于使用字符串搜索在多维数组中查找坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!