在Javascript中获取多维数组中元素的坐标

时间:2019-03-13 15:00:09

标签: javascript search multidimensional-array indexof

我想将元素放置在像这样的多维数组中的位置:

    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 coordinates = letterVariations.indexOf('u');
	console.log(coordinates);
	// Want to know that 'u' is 7 in the 7th array

有可能吗?

2 个答案:

答案 0 :(得分:1)

运行一个简单的for循环,并使用indexOf检查字符是否在内部数组中。找到匹配项后立即返回

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', '”'],
  ['@', '&', '#', '[', '(', '/', ')', ']', '+', '=', '-'],
];

function getCoordinates(array, char) {
  for (let i = 0; i < array.length; i++) {
    const i2 = array[i].indexOf(char);
    if (i2 !== -1)
      return [i, i2]
  }
  return undefined
}

console.log(getCoordinates(letterVariations, 'u'))
console.log(getCoordinates(letterVariations, '@'))

注意:这将返回索引,并且它从零开始。如果您想要[7, 7],则需要返回[i+1, i2]

答案 1 :(得分:0)

  

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

     

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

const 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','”'],
		['@','&','#','[','(','/',')',']','+','=','-'],
];

function getIndexOfLetter(letter) {
  return letterVariations.reduce((result, values, index) => {
    if (result[0] > -1) return result;

    const found = values.indexOf(letter);

    return found > -1 ? [Number(index), found] : result;
  }, [-1, -1])
}

console.log(getIndexOfLetter('k'))