解构返回未定义

时间:2017-10-24 17:36:59

标签: javascript arrays destructuring

我试图将对象作为参数传递给函数,然后该函数将对象的属性推送到数组,然后方法将向控制台显示添加的值。它成功创建了我传递的对象实例,但属性未定义。我哪里做错了? 这是我的代码:

let myApp =(function() {
    let personProps = {
       firstName: null,
       lastName: null,
       Age: null,
    }
    let university = {
       numberOfSutdents : null,
       numberOfStaff : null,
       sections : ['Gumamela', 'St. Anne', 'St. John'],
       students : [],
       staff: []
    }

    let staff = Object.create(personProps);
    staff.hireDate = null;
    staff.rule = null;

    let faculty = Object.create(staff);
    faculty.subjectTeaching = null;
    faculty.NumberOfSectionsCovered = null;

    let student = Object.create(personProps);
    student.section = null;
    student.year = null;
    student.yeadEnrolled = null;

    // Checks if staff is a prototype of university
    let h = Object.getPrototypeOf(student) === personProps ? true : false;

    // CMDS
    let addStudent = ({_fn , _ln, _age}) => {
       let _student = [
          student.firstName = _fn,
          student.lastName = _ln,
          student.Age = _age
        ]
        university.students.push(_student)
     }

    //Query
    let getStudents = () => {
        return console.log(university.students)
      }

     return {  
        addStudent,
        getStudents
     }
})();


myApp.addStudent({fisrtName: 'marven', lastName: 'donque', Age: 22})
myApp.addStudent({fisrtName: 'john', lastName: 'tompson', Age: 23})

myApp.getStudents();


// it returns 2 instance of array, but with 3 undefined properties.

2 个答案:

答案 0 :(得分:2)

您的参数名称应符合:

所以你必须把它改成:

let addStudent = ({firstName , lastName, Age}) => {
   let _student = [
      student.firstName = firstName,
      student.lastName = lastName,
      student.Age = Age
    ]
    university.students.push(_student)
 }

在打电话的时候:

myApp.addStudent({fisrtName: 'marven', lastName: 'donque', Age: 22});

这将完全正常。

答案 1 :(得分:0)

正如解构对象时的注释中所述,变量名必须与对象中键的名称完全匹配。当你创建学生for item in film: button = Button(master=aanbiederspage, text=item, command= lambda: filmdatabase(item)).pack() 应该是fisrtName并且在firstName不需要时返回时,也会出现拼写错误。



console.log