如何在Javascript中创建动态变量? [英] How to create dynamic variables in Javascript?

查看:90
本文介绍了如何在Javascript中创建动态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开展一个非盈利项目,该项目跟踪来电和拨出电话的信息。我完全用HTML,Javascript创建了它。

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:'',     
   }
}

这种架构一次只支持3个电话。我怎样才能让它变得动态?我的意思是我可以动态生成这些变量吗?

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?

推荐答案

由于 call1 call2 等等,有点多余,最好将数据存储在数组而不是对象中。我推荐这个(对象将在数组中自动编号)。 现场演示(点击)。

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.

这篇关于如何在Javascript中创建动态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆