检查数据是否在数组中

时间:2016-12-05 14:21:05

标签: javascript

我正在尝试创建一个if语句来检查输入数字是否在现有数组中。

我想要实现的是我可以在输入字段中插入一个数字并从数组中删除它。我想知道最好的方法是什么。

var nummers = [20, 14, 39, 192, 39];
toon();

// button's maken
document.getElementById("addOneBtn").onclick = addNum;
document.getElementById("removeOneBtn").onclick = removeNum;
document.getElementById("sorteerBtn").onclick = sorteer;
document.getElementById("sorteer2Btn").onclick = sorteer2;

function addNum() {
  var num = document.getElementById("addOneInput").value;
  //nummers.push(" " + num);
  nummers.push(parseInt(num));
  toon();
}

function removeNum() {
  if (document.getElementById("removeOneInput").value in nummers) {
    nummers.pop();
    toon();
  } else {
    document.getElementById("removeOneError").innerHTML = "not a number or in the array"
  }
}

function sorteer() {
  nummers.sort(vergelijk);
  toon();
}

function sorteer2() {
  nummers.sort(vergelijk2);
  toon();
}

function vergelijk(a, b) {
  return a - b;
}

function vergelijk2(a, b) {
  return b - a;
}


function toon() {
  document.getElementById("arrayOutput").innerHTML = nummers.toString(); //renault.gegevens()
}
<p id="arrayOutput"></p>
<br>
<input type="input" id="addOneInput">
<button type="button" value="add one" id="addOneBtn">Add one number</button>
<br>
<br>
<input type="input" value="" id="removeOneInput">
<p id="removeOneError"></p>
<button type="button" value="remove one" id="removeOneBtn">Remove a number</button>
<br>
<br>
<button type="button" value="sorteer" id="sorteerBtn">Sorteer</button>
<button type="button" value="sorteer omgekeerd" id="sorteer2Btn">Sorteer andersom</button>

0 个答案:

没有答案