简体   繁体   中英

Why is this array undefined in my javascript?

When trying to run this webpage using the following javascript I am continually getting thrown that the namesInAttendance array is undefined. I am not seeing what is wrong here. Help? Please?

// Parse out the given contestants into an array
var name = $('#contestant_names').val().split(/\n/);
var namesInAttendance = [];
for (var i = 0; i < namesInAttendance.length; i++)
{
    // This keeps any white space from being pushed into the array
    if(/\S/.test(name[i]))
    {
        namesInAttendance.push($.trim(name[i]));
    }
}

// Alerts the user if not enough names are entered for the race.
if (namesInAttendance.length < 6 || namesInAttendance.empty())
{
    alert("Sorry, please make sure that at least 6 contestants are available.");
}

I think the code should be

// Parse out the given contestants into an array
var name = $('#contestant_names').val().split(/\n/);
var namesInAttendance = [];

// ----------------------------------------------------------------------
// Here the loop variable should be name, not namesInAttendance
// Since namesInAttendance is empty when you first create it.
// And your attention is to copy data from name to namesInAttendance.
// I think it's better to check whether name is defined firstly as below
// ----------------------------------------------------------------------
if (name != undefined && name.length > 0) {
    //-->namesInAttendance.length -> name.length
    for (var i = 0; i < name.length; i++) 
    {
        // This keeps any white space from being pushed into the array
        if(/\S/.test(name[i]))
        {
            namesInAttendance.push($.trim(name[i]));
        }
    }
}

// Alerts the user if not enough names are entered for the race.
if (namesInAttendance.length < 6)
{
    alert("Sorry, please make sure that at least 6 contestants are available.");
}

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