【问题标题】:Pushing Object to an empty array where the value of one Object key is based on the empty array, with a function将 Object 推送到一个空数组,其中一个 Object 键的值基于空数组,带有一个函数
【发布时间】:2021-03-19 13:02:59
【问题描述】:

我有一项需要帮助的任务。 (我试图用我的母语翻译这个作业,所以我希望它仍然可以理解)

赋值是一个CRUD函数问题,如下:

  1. 为员工创建对象模板(身份证、姓名、年龄)
  2. 创建一个接收对象参数作为参数的函数
  3. 输出应该是成功的(布尔值)

这是老师给我们的开始:

let employee = [];

// create blueprint here

// create -> insert data of new employee. receives parameter object
function create(employee_data){
    // write your logic here
}

create(new Employee(employee[employee.length-1].id + 1, "Vincent", 25));

//output: success(boolean)

现在我还没有创建 create- 函数,因为我想先手动尝试。但是我仍然不知道怎么做,因为输入 id 总是出错,因为它是基于空的员工 []

let employee = [];

//=========== TEMPLATE 
class Employee {
  constructor(id, nama, age) {
    this.id = id;
    this.nama = nama;
    this.age = age;
  }
}
//=========== TEMPLATE 

console.log(employee);

employee.push(
  new Employee(
    employee[employee.length-1].id + 1,
    "Vincent",
    25
  )
);
console.log(employee[0]);


提前致谢

【问题讨论】:

  • 我认为您应该自行决定填写此数组
  • employee 数组最初是空的,访问 undefined 的 id 会抛出错误。您可以将此(employee[employee.length-1]?.id ?? 0) + 1 作为第一个参数传递。或者你可以第一次传递1,然后你可以使用employee[employee.length-1].id + 1
  • employee[employee.length-1].id 将在您第一次推送时返回 undefined

标签: javascript arrays oop object crud


【解决方案1】:

尝试使用employee.length + 1 作为新创建的员工对象的id

参考下面

let employee = [];


//=========== TEMPLATE 
class Employee {
  constructor(id, nama, age) {
    this.id = id;
    this.nama = nama;
    this.age = age;
  }
}
//=========== TEMPLATE 

function create(employee_data){
  // write your logic here
  employee.push(employee_data)
  return true;
}

const newEmployee = new Employee(employee.length+1, "Vincent", 25)
create(newEmployee);


//console.log(employee);

// employee.push(
//   new Employee(
//     employee[employee.length-1].id + 1,
//     "Vincent",
//     25
//   )
// );
console.log(employee[0]);

【讨论】:

    猜你喜欢
    • 2019-12-29
    • 2015-07-26
    • 2014-02-04
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2017-09-25
    相关资源
    最近更新 更多