检查用户输入是否等于数组值

时间:2017-10-06 10:56:18

标签: javascript arrays

我有一些代码可以将用户输入与数组中的值进行比较。如果用户输入匹配,我想显示一个等于输入值的img。

像这样:用户输入字母A,A等于字母[0],所以显示img A.png。

已经尝试了一段时间,但似乎无法让它工作?我需要使用关联数组

window.onload = btn;

function btn() {
  document.getElementById("btn").onclick = generateLetters;
}

// Array containing every letter in the alphabet
var letters = ["A", "B", "C", "D", "A", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Æ", "Ø", "Å"];

// Array containing a img equal to the letter
var letterImages = [letters[0] = "img/A.png", letters[1] = "img/B.png", letters[2] = "img/C.png", letters[3] = "img/D.png"];

function generateLetters() {

  // Get user input and convert to upper case to match array value
  var input = document.getElementById("input").value.toUpperCase();
  // Loops through letterImages array
  for (var x = 0; x < letterImages.length - 1; x++)

    // Loops through letters array
    for (var i = 0; i < letters.length; i++)
      // Check if input is equal to a value inside letters array
      if (letters.indexOf(input) > -1) {
        // Show img equal to input value
        document.getElementById("img").src = letters[x];
      }
}
<input id="input" type="text">
<button id="btn" type="button">Generate Letter</button>
<p id="print"></p>
<img id="img" height="50px" width="50px">

3 个答案:

答案 0 :(得分:1)

您可以使用Object数组保存每个字母和相关图像:

$( "#btn" ).click(function() {
    var letters = [ 
    { letter: "A", img: "https://dummyimage.com/600x400/000/fff&text=One" },
    { letter: "B", img: "https://dummyimage.com/600x400/874787/0011ff&text=Two" },
    { letter: "C", img: "https://dummyimage.com/600x400/a697a6/6569ab&text=Three" }
];

// Get user input and convert to upper case to match array value
var input = document.getElementById("input").value.toUpperCase();

var found = letters.find(l => l.letter === input);

if (found) {
    document.getElementById("img").src = found.img;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input" type="text">
<button id="btn" type="button" click="displayimg();">Generate Letter</button>
<p id="print"></p>
<img id="img" height="50px" width="50px">

答案 1 :(得分:0)

您可以这样简单地构建阵列。

var letterImages = [{"a": "img/A.png"}, {"b":"img/B.png"}, 
{"c": "img/C.png"}, {"d":"img/D.png"}];

function generateLetters() {

  // Get user input and convert to upper case to match array value
  var input = document.getElementById("input").value.toUpperCase();
  var item = letterImages.find((item) => item[input])

  if (item) {
    // Show img equal to input value
    document.getElementById("img").src = item[input];
  }
}

答案 2 :(得分:0)

如果输入和文件名之间存在1-1相关性,则可以取消所有循环和数组。只需检查输入是否在A和Z之间,如果是,则使用该输入添加图像源。

if (/[A-Z]/.test(input)) {
  document.getElementById("img").src = `img/${input}.png`;
}