gpt4 book ai didi

javascript - 为什么我的变量未定义

转载 作者:行者123 更新时间:2023-11-30 11:41:24 24 4
gpt4 key购买 nike

我有这个功能

    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"};
}

然后在 body 中我尝试这样做:

        var students = getStudents();

var referrals = ["James", "Angela"];
for(var i = 0; i < students.length; i++){
var pTag ="<p>";

但是,当我尝试通过循环时,它告诉我它不能执行 .length of an undefined variable,但我认为我已经通过调用函数并将其分配给变量来定义它?

最佳答案

更改此代码的函数。问题是您没有返回变量 students 并且当您超出范围时该变量不再存在。通过返回,您将在调用函数时将其分配给变量。

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;
}

关于javascript - 为什么我的变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42507104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com