2017-05-09 74 views
0

我有一个简单的时间输入表,在这里看到:https://codepen.io/dikuw/pen/rmpozm在对象中保存动态数据?

我想动态存储时间数据为用户添加,修改和删除行正在考虑的对象是最好的办法。

我的问题是最佳做法是什么?我应该创建一个构造函数,例如

function TimesheetRecord(id, TSDate, TSStaffId, Hours, Comments, TSTaskId, Billable) { 
    this.id = id; 
    this.TSDate = TSDate; 
    this.TSStaffId = TSStaffId; 
    this.Hours = Hours; 
    this.Comments = Comments; 
    this.TSTaskId = TSTaskId; 
    this.Billable = Billable; 
} 

然后每次用户添加一行时动态创建一个新对象?如果我这样做,我怎么知道有多少物体?

+1

为了创建简单的对象'{'key':value}''符号会更加容易和快速。 –

+1

使用'set'或'array'来存储对象,然后对其中的元素进行计数。 – Slime

+1

把它们放入数组中? –

回答

1

在这里,您可以创建一个数组来存储所有TimesheetRecords,并在创建新动态对象时推送新的动态对象。

// When app starts (dataFromDB is data fetched from db if any) 
const TimesheetRecords = dataFromDB || [] 

// create a new record(mainly in a function) 
const TimesheetRecord = { 
    id: id, 
    TSDate: TSDate, 
    TSStaffId: TSStaffId, 
    Hours: Hours, 
    Comments: Comments, 
    TSTaskId: TSTaskId, 
    Billable: Billable 
} 

// store to db (ajax) and then push to array 
TimesheetRecords.push(TimesheetRecord) 

// Check how many records are there 
const count = TimesheetRecords.length 

这是存储JavaScript中没有任何行为(方法)的简单对象的常用模式。