我有这个功能
function getStudents() {
var students = [];
students[0] = {name: "Anna", mark: 65, sex: "female"};
students[1] = {name: "James", mark:33, sex: "male"};
students[2] = {name: "William", mark: 87, sex: "male"};
students[3] = {name: "Jane", mark: 72, sex: "female"};
students[4] = {name: "Rikki", mark: 60, sex: "male"};
students[5] = {name: "Angela", mark: 58, sex: "female"};
}
然后在身体中我尝试这样做:
var students = getStudents();
var referrals = ["James", "Angela"];
for(var i = 0; i < students.length; i++){
var pTag ="<p>";
然而,一旦我尝试通过循环,它告诉我它不能做.min的未定义变量,但我想我已经通过调用函数并将其分配给变量来定义它?
答案 0 :(得分:3)
更改此代码的功能。问题是你没有返回变量学生,当你超出范围时,变量不再存在。返回时,您将在调用函数时将其分配给变量。
function getStudents() {
var students = [];
students[0] = {name: "Anna", mark: 65, sex: "female"};
students[1] = {name: "James", mark:33, sex: "male"};
students[2] = {name: "William", mark: 87, sex: "male"};
students[3] = {name: "Jane", mark: 72, sex: "female"};
students[4] = {name: "Rikki", mark: 60, sex: "male"};
students[5] = {name: "Angela", mark: 58, sex: "female"};
return students;
}
答案 1 :(得分:1)
你应该echo $don;
变量
void f() {
d();
}
void d() {
}
答案 2 :(得分:0)
您需要在函数末尾返回students数组,以便从getStudents为变量分配数组:
function getStudents() {
var students = [];
students[0] = {name: "Anna", mark: 65, sex: "female"};
students[1] = {name: "James", mark:33, sex: "male"};
students[2] = {name: "William", mark: 87, sex: "male"};
students[3] = {name: "Jane", mark: 72, sex: "female"};
students[4] = {name: "Rikki", mark: 60, sex: "male"};
students[5] = {name: "Angela", mark: 58, sex: "female"};
return students;
}
否则你说var students = getStudents();
它只是在做函数调用而不是分配数组。
答案 3 :(得分:-1)
您无法在创建对象的函数调用中请求未返回的对象的长度。您没有为学生变量分配任何内容,因为getStudents()函数不会返回值或对象,从而导致您获得错误。
在下面的jsfiddle上使用开发者控制台来查看演示
function getStudents() {
var students = [];
students[0] = {name: "Anna", mark: 65, sex: "female"};
students[1] = {name: "James", mark:33, sex: "male"};
students[2] = {name: "William", mark: 87, sex: "male"};
students[3] = {name: "Jane", mark: 72, sex: "female"};
students[4] = {name: "Rikki", mark: 60, sex: "male"};
students[5] = {name: "Angela", mark: 58, sex: "female"};
return students;
}
var students = getStudents();
//var referrals = ["James", "Angela"];
console.log(students);