简体   繁体   中英

simple arrays and conditions javascript

So im a newbie and I need some basic help. I wanna make a program that checks whether room is free or taken. I dont know if i can make just a variable with all free rooms or should i do this the other way. I'm kinda stuck on solving the problem.

function action() {
    var room = document.getElementById('text');
    var free = [1, 2, 3];
    if (room.value == free) {
        alert('Hello');
    } else {
        alert('Taken');
    }
}

document.getElementById('button').onclick = function() {
    action();
}

I wanna ask if is it possible to just compare variable i enter to other variable with list of free rooms if not, how to make this work then?

You can't just compare your number with an array. You need to check if your number is in the array:

if (free.indexOf(room.value) > -1)

Also, assuming you're using a text field, you'll need to convert room.value to a Number (instead of String) before checking:

if (free.indexOf(+room.value) > -1)

You can learn more about indexOf() on MDN.

The line if (room.value == free) compares a string (the value) with an array . That won't usually be true.

To find a value in an array, you use Array#indexOf . It does strict comparison, so since your values in the array are numbers, you have to make sure that your value is a number as well.

So

if (free.indexOf(+room.value) != -1) {
    // Yes it's there
}

The unary + is one way to convert strings to numbers. Another is parseInt , which lets you specify a radix (number base):

if (free.indexOf(parseInt(room.value, 10)) != -1) {
    // Yes it's there
}

You have other options as well; this answer lists the various options and the pros and cons of them.

You can try this. Going further, you can remove the room number taken from the list of free rooms and push them into list of rooms already taken.

 function action() { var isRoomAvailable = false; var room = document.getElementById('text').value; var freeRoom = [1, 2, 3]; // 4-10 are taken rooms. var takenRooms = [4, 5, 6, 7, 8, 9, 10]; for (var i = 0; i < freeRoom.length; i++) { if (room == freeRoom[i]) { alert('Hello, You can take room '+room); isRoomAvailable = true; return; } } if (!isRoomAvailable) alert("Sorry, Room number " + room + " is taken"); } document.getElementById('button').onclick = function() { action() } 
 Enter Room number(1-10): <input type="text" id="text" /> <button id="button">Search Room</button> 

You should perhaps use a 0 and 1 system for storing whether a room is taken. So 0 is for taken and 1 is for free or vice versa depending on your liking. So all it would have to do is test for whether in the array, the room's value is 0 or 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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