当尝试使用以下javascript运行此网页时,我不断被抛出,nameInAttendance数组未定义。我没有看到这里有什么问题。救命?请?
// 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.");
}
答案 0 :(得分:1)
我认为代码应该是
// 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.");
}