I am wanting to create a very simple script that checks user's input to a pre-existing array. However, it doesn't seem to work and I'm not sure why. Please, keep in mind I'm new to this and trying to learn.
<script>
var usernumber = prompt('What is your number?');
var numbers = ['1', '2', '3'];
if (usernumber == 'numbers') //If the user number matches one of preset numbers
{
alert('Match');
} else {
alert('No match found.');
}
</script>
I am wanting to create a very simple script that checks user's input to a pre-existing array. However, it doesn't seem to work and I'm not sure why. Please, keep in mind I'm new to this and trying to learn.
<script>
var usernumber = prompt('What is your number?');
var numbers = ['1', '2', '3'];
if (usernumber == 'numbers') //If the user number matches one of preset numbers
{
alert('Match');
} else {
alert('No match found.');
}
</script>
Share
Improve this question
asked Nov 13, 2017 at 14:33
rebirthreliverebirthrelive
111 silver badge2 bronze badges
3
- Possible duplicate of How do I check if an array includes an object in JavaScript? – cнŝdk Commented Nov 13, 2017 at 14:37
- You should explain what exactly it's doing incorrectly, versus what you want. – user3556757 Commented Nov 13, 2017 at 14:38
- You're going to find that there are many ways to skin this cat. If you visit: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… You can learn about how to manipulate your array and choose the best solution for what you're attempting to do. – Chris Commented Nov 13, 2017 at 14:42
5 Answers
Reset to default 4You can use Array.indexOf prototype function here:
if(numbers.indexOf(usernumber) >= 0){
alert('Match');
}
Reference: https://developer.mozilla/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
this will work fine for you
<script>
var usernumber = prompt('What is your number?');
var numbers = ['1', '2', '3'];
for(i=0;i<=numbers.length;i++)
{if (usernumber == numbers[i])
{
alert('Match');
break;
} }
if(i==numbers.length) {
alert('No match found.');
}
</script>
You can check the following code
var usernumber = prompt('What is your number?');
var numbers = ['1', '2', '3'];
if (numbers.indexOf(usernumber) >=0 ) //If the user number matches one of preset numbers
{
alert('Match');
} else {
alert('No match found.');
}
array.indexof(item) return -1 if the item does not exist on the array else return item's index
<script>
var usernumber = prompt('What is your number?');
var numbers = ['1', '2', '3'];
if (numbers.indexOf(usernumber) >=0 ) // check if the item exists on the array
{
alert('Match');
} else {
alert('No match found.');
}
</script>
<script>
var usernumber = prompt('What is your number?');
var numbers = new Array();
numbers['1'] = true;
numbers['2'] = true;
numbers['3'] = true;
if (numbers[usernumber]) //If the user number matches one of preset numbers
{
alert('Match');
} else {
alert('No match found.');
}
</script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744763948a4592340.html
评论列表(0条)