[英]javascript - create new (global) objects with names from array
i am trying to create new Objects with names out of an array. 我试图用数组名称创建新对象。 Without an array i would do:
没有数组,我会做:
var object_bruno = new Object();
var object_carlos = new Object();
var object_luci = new Object();
so i will end up with 3 new Objects. 所以我最终会得到3个新对象。 But why wont we do that with an loop, which makes it more easy to adde some more Objects later.
但是,为什么不使用循环来做到这一点呢?这使得以后添加更多对象变得更加容易。 So i ttried:
所以我试了一下:
// an array full of object names
var obj_arr = [ "object_bruno", "object_carlos", "object_luci"];
// Method one:
for (x in obj_arr) {
alert(obj_arr[x]); // right names shown
var obj_arr[x] = new Object(); //syntax error, dosent work??
};
// Method two:
obj_arr.forEach(function(func_name) {
alert(func_name); // right names
var func_name = new Object(); // no objects are created ???
});
basicly i would prefer to use Method two. 基本上,我更喜欢使用方法二。 i like it because i can fill them late the same way?
我喜欢它,因为我可以用同样的方法加满它们? hopefuly?
充满希望吗? Any ideas what wents wrong?
任何想法出了什么问题吗?
You can just loop over the array and assign a new Object
to each of the items , like this: 您可以在数组上循环并为每个项目分配一个
new Object
,如下所示:
for (var i = 0, l = obj_arr.length; i < l; i++) {
obj_arr[i] = {};
}
UPDATE 更新
You can also do it in this way by applying properties to the global
object, for example window
: 您也可以通过将属性应用于
global
对象(例如window
来以这种方式进行操作:
var people = [ "object_bruno", "object_carlos", "object_luci"];
for (var i = 0, l = people.length; i < l; i++) {
global[people[i]] = {};
}
Using this solution makes the objects global, so you can use them like object_bruno
. 使用此解决方案可使对象成为全局对象,因此您可以像
object_bruno
一样使用它们。
Another improvement can be the usage of computed propertiey names
of ECMAScript 2015: 另一个改进可以是使用ECMAScript 2015的
computed propertiey names
:
var people = [ "bruno", "carlos", "luci"], prefix = 'object_';
for (var i = 0, l = people.length; i < l; i++) {
global[prefix + people[i]] = {};
}
This allows to have more meaningful array. 这允许具有更有意义的数组。
Note, the global
can be the window
object in browsers or global
object in NodeJS, or perhaps something else in other environments. 注意,
global
可以是浏览器中的window
对象,也可以是NodeJS中的global
对象,或者在其他环境中也可以是其他对象。
Because you are creating a new variable by declaring 因为您通过声明来创建新变量
obj_arr.forEach(function(func_name) {
alert(func_name); // right names
var func_name = new Object(); // no objects are created ???
});
try this 尝试这个
obj_arr.forEach(function(func_name) {
alert(func_name); // right names
func_name = new Object(); // no objects are created ???
});
var obj_arr = [ "object_bruno", "object_carlos", "object_luci"];
obj_arr.forEach(function(func_name, index, arr) {
arr[index] = {};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.