简体   繁体   English

为什么这个数组在我的 javascript 中未定义?

[英]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.尝试使用以下 javascript 运行此网页时,我不断收到未定义 namesInAttendance 数组的消息。 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.");
}

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

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