0

I am working on a non-profit project, which tracks information of Incoming calls and outgoing calls. I created that completely in HTML, Javascript.

To store the caller phone number I do created a namespace as follows:

var allCalls={
   call1={
     phonenumber:'',     
   },
   call2={
     phonenumber:'',     
   },
   call3={
     phonenumber:'',     
   }
}

with this architecture it only supports 3 calls at a time. How can I make it dynamic? I mean can I generate these variables dynamically?

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
user3191903
  • 237
  • 2
  • 6
  • 14

1 Answers1

2

Since call1, call2, etc, is a bit redundant, it is best to store data that is associated numerically in an array rather than an object. I recommend this (the objects will be auto-numbered in the array). Live demo (click).

var calls = [];

function foo(phone) {
  return { phoneNumber: phone };
}

//call comes in
var call = foo('555-555-5555');
calls.push(call);

console.log(calls[0]); //0 is the first item.

//another call comes in
var call = foo('555-123-4567');
calls.push(call);

console.log(calls[1]); //etc

Note that I abstracted the created of the object into a function so as to keep things uniform, maintainable, and DRY.

m59
  • 43,214
  • 14
  • 119
  • 136