简体   繁体   中英

Javascript - pushing values into an array returns undefined

new with javascript here. I have a simple form that takes what the user submits and puts it into an array. When a specific word is submitted, a prompt comes up with a random value from the array. The problem I think I'm having here is that things aren't actually being pushed into the array, as the prompt will return undefined.

var res_array = [];
var restaurant = document.getElementById("restaurants");
var rand = res_array[Math.floor(Math.random() * res_array.length)];

function submit_res(){
    if (restaurants.value !="end" && restaurants.value !="finish") {
        alert('It got pushed');
        res_array.push(restaurant);
        return true;
    } else {
        alert('Selected restaurant: ' + rand);
    }
}

Now here is the fixed up one --

var res_array = [];

function submit_res(){
var restaurant = document.getElementById("restaurants");

if (restaurants.value !="end" && restaurants.value !="finish") {
    res_array.push(restaurant.value);
} else {
    var random_res = res_array[Math.floor(Math.random() * res_array.length)];
    alert('Selected restaurant: ' + random_res);
}

return false;
}

HTML parts:

<form>
    Restaurants: <input type="text" id="restaurants" name="restaurants" />
    <input type="submit" value="Submit" onClick="return submit_res()"/>
</form>

Things are being pushed into the array, but they're not taken out again.

The snippet res_array[Math.floor(Math.random() * res_array.length)]; is executed only once, before the user submits any values. res_array is empty at this time, so taking a random element from it results in undefined . This is what is prompted.

The solution is to move var rand = res_array[...]; into the else {} clause.

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