我可以在JavaScript中创建动态对象名称吗? [英] Can I create dynamic object names in JavaScript?

查看:83
本文介绍了我可以在JavaScript中创建动态对象名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

javascript - 动态变量

动态Javascript变量名称

我需要在页面上创建多个对象,并希望按顺序命名它们。有没有办法在JavaScript中执行此操作?

I need to create a number of objects on a page and want to name them sequentially. Is there a way to do this in JavaScript?

for (i=0;i<num;i++){
  var obj+i = new myObject("param1","param2");
  obj+i.someProperty = value;
}

这样我可以动态创建不同数量的对象(取决于值) num)然后适当地设置它们的属性。

This way I can dynamically create a varying number of objects (dependent on the value "num") and then set their properties appropriately.

我可以在PHP中执行此操作,有没有办法在JavaScript中执行此操作?

I can do this in PHP, is there a way to do it in JavaScript?

推荐答案

这不是推荐的,而是你要做的事情(如果你在浏览器而不是其他一些js环境中运行)。

This isn't recommended, but does what you're trying to do (if you're running in a browser and not some other js environment).

for (i = 0; i < num; i++) {
  window['obj' + i] = new myObject("param1","param2");
  window['obj' + i].someProperty = value;
}
obj0.someProperty;

这是有效的,因为全局变量实际上是窗口对象的属性(如果你在浏览器中运行) )。您可以使用点表示法(myObject.prop)或括号表示法(myObject ['prop'])访问对象的属性。通过分配窗口['obj'+ i],您将创建一个名为'obj'+ i的全局变量。

This works because global variables are actually properties of the window object (if you're running in the browser). You can access properties of an object using either dot notation (myObject.prop) or bracket notation (myObject['prop']). By assigning window['obj' + i], you're creating a global variable named 'obj' + i.

更好的选择是使用数组或父级用于存储对象的对象。

The better option is to use an array or parent object to store your objects.

myObjs = {};
for (i = 0; i < num; i++) {
  myObjs['obj' + i] = new myObject("param1","param2");
  myObjs['obj' + i].someProperty = value;
}
myObjs.obj0.someProperty;

或使用像许多其他答案建议的数组。

Or use an array like lots of other answers suggest.

这篇关于我可以在JavaScript中创建动态对象名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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