简体   繁体   English

检查 JavaScript 数组中是否存在数字输入值

[英]Check if numeric input value exists in an array in JavaScript

I am trying to check if a number entered exists in an array.我正在尝试检查输入的数字是否存在于数组中。 I've tried many things and haven't got anything to work.我已经尝试了很多东西,但没有任何工作。

function start() {
    var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
    var input = document.getElementById('input').value;
    var numberExist = document.getElementById('numberExist').innerHTML;

    for (var i = 0; i < arrNum.length; i++) {
        if (input === arrNum[i]) {
            alert('input');
            numberExist = ('The number ' + input + 'exists in the array');
        } else {
            numberExist = ('The number ' + input + 'does not exist in the array');
        }
    }

    var arrNum = arrNum.join(' ');
    document.getElementById('listOfvalues').innerHTML = ('The values in the array are ' + arrNum);
}

Here are a few pointers:这里有一些提示:

  • You need to cast your input.value to an integer, eg using the unary + operator, because the HTMLInputElement#value property returns a string.您需要将input.value转换为整数,例如使用一元+运算符,因为HTMLInputElement#value属性返回一个字符串。
  • Your else block will run on the first for-loop iteration unless you move it outside of the loop body.else ,除非你外面移动它的循环体块将第一个for循环迭代运行。

 function start() { var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20] var input = +document.getElementById('input').value var numberExist for (var i = 0; i < arrNum.length; i++) { if (input === arrNum[i]) { numberExist = 'The number ' + input + ' exists in the array' } } if (!numberExist) { numberExist = 'The number ' + input + ' does not exist in the array' } document.getElementById('listOfvalues').textContent = 'The values in the array are ' + arrNum.join(' ') document.getElementById('numberExist').textContent = numberExist } start()
 <input type="number" id="input" value="18"> <div id="listOfvalues"></div> <div id="numberExist"></div>

Of course, as others have pointed out, this example can be greatly simplified using the Array#indexOf method:当然,正如其他人指出的那样,使用Array#indexOf方法可以大大简化此示例:

 function start() { var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20] var input = +document.getElementById('input').value var numberExist = array.indexOf(input) < 0 ? 'The number ' + input + ' does not exist in the array' : 'The number ' + input + ' exists in the array' document.getElementById('listOfvalues').textContent = 'The values in the array are ' + array.join(' ') document.getElementById('numberExist').textContent = numberExist } start()
 <input type="number" id="input" value="18"> <div id="listOfvalues"></div> <div id="numberExist"></div>

Try indexOf function Eg:试试indexOf函数 例如:

arr = [1, 4, 18, 5, 10];
arr.indexOf(4); //returns 4
arr.indexOf(20); //returns -1

Use indexOf method使用indexOf方法

var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];

function checkNumber(x){
 if(arrNum.indexOf(x)!=-1){
    alert('number exist')
 }
 else{
 alert('dont exist')
 }

}
checkNumber(8) // alert don't exist

Array prototype has a method indexOf which returns the index of the element, if such exists, -1 otherwise.数组原型有一个indexOf 方法,它返回元素的索引,如果存在,否则 -1。

In ES6 includes method is added, which returns true/false depending on element's existence.在 ES6 中添加了includes 方法,它根据元素的存在返回真/假。

Try this:试试这个:

 function checkIfExists(arr, num){ for (var i = 0; i < arr.length; i +=1){ if(num === arr[i]){ return true; } } return false; } var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20]; var userInput = document.getElementById('user-input'); arrNumStr = arrNum.join(","); document.getElementById('listOfvalues').innerHTML = ('The values in the array are ' + arrNumStr); document.getElementById('check').onclick = function () { var input = Number(userInput.value); // Using Number to convert from string to number //if (arrNum.indexOf(input) > -1) if (checkIfExists(arrNum,input)){ alert('Number is exists') }else{ alert('Number not exists'); } }
 <input type="text" id="user-input"> <br> <input type="button" id="check" value="Check"> <br> <div id="listOfvalues" ></div>

convert input value to number which is by default string.input值转换为默认字符串的数字。

var input = +document.getElementById('input').value;
//OR input = Number(document.getElementById('input').value);
//OR input = parseInt(document.getElementById('input').value, 10);

break the loop if number is found, do not continue running the loop.如果找到数字,则中断循环,不要继续运行循环。

if (input === arrNum[i]) {
        numberExist.innerHTML = ('The number ' + input + ' exists in the array');
        break;
    }

 window.onload = start; function start() { var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20]; var input = +document.getElementById('input').value; var numberExist = document.getElementById('numberExist'); for (var i = 0; i < arrNum.length; i++) { if (input === arrNum[i]) { numberExist.innerHTML = ('The number ' + input + ' exists in the array'); break; } else { numberExist.innerHTML = ('The number ' + input + ' does not exist in the array'); } } var arrNum = arrNum.join(' '); document.getElementById('listOfValues').innerHTML = ('The values in the array are ' + arrNum); }
 <input type="number" id="input" value="18" onblur="start()"/> <button onclick="start()">Check</button> <div id="numberExist"></div> <div id="listOfValues"></div>

Strict equality operator compares types: Which equals operator (== vs ===) should be used in JavaScript comparisons?严格相等运算符比较类型:在 JavaScript 比较中应该使用哪个等于运算符 (== vs ===)? . .

 console.log("1 == 1 is", 1 == 1); console.log("1 == \\"1\\" is", 1 == "1"); console.log("1 === 1 is", 1 === 1); console.log("1 === \\"1\\" is", 1 === "1"); console.log("1 === parseInt(\\"1\\", 10) is", 1 === parseInt("1", 10));

This can now be done with the 'includes' method (not in Edge 13 or earlier).这现在可以通过“包含”方法完成(不在 Edge 13 或更早版本中)。

if( arr.includes(valueToFind) ){

w3schools w3schools

Try to use Number() function.尝试使用Number()函数。 Such as Number(input) .例如Number(input) Since you input box type is not Number .由于您输入的框类型不是Number Thus in input variable you are always getting string.因此在input变量中你总是得到字符串。 Thus you need to convert the string to numeric.因此,您需要将字符串转换为数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM