javascript 在循环中创建新的对象实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14177573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:55:38  来源:igfitidea点击:

Creating new object instances in a loop

javascript

提问by Phil

I'm trying to create a new object for each item in an array by looping. The names of the objects should be based on the key of the array.

我正在尝试通过循环为数组中的每个项目创建一个新对象。对象的名称应基于数组的键。

So for this array:

所以对于这个数组:

var arr = new Array(
    "some value",
    "some other value",
    "a third value"
);

Would result in three objects:

将导致三个对象:

alert(object1.value);
alert(object2.value);
alert(object3.value);

The code I have thus far (but isn't working) is:

到目前为止我拥有的代码(但不起作用)是:

// Object
function fooBar(value) {
    this.value = value;
    ...
}

// Loop
var len = arr.length;
for (var i = 0; i < len; i++) {
    var objectName = object + i;
    var objectName = new fooBar(arr[i]);
}

Does what I'm asking for even make sense?

我所要求的甚至有意义吗?

回答by u8sand

You have to make an array of the objects also

您还必须制作一个对象数组

var objs = new Array();

for(var i = 0; i < len; i++) {
  objs[i] = new fooBar(arr[i]);
}

alert(objs[0].value);

回答by Ted Hopp

You can map your array:

您可以映射您的数组:

var arr = new Array(
    "some value",
    "some other value",
    "a third value"
);
var fooBars = arr.map(function(x) { return new fooBar(x); });

Then you can access each value:

然后您可以访问每个值:

alert(fooBars[0].value);
// etc.

or process them all at once:

或同时处理它们:

fooBars.forEach(function (foo) { alert(foo.value); });

回答by Norguard

What you're asking for makes sense, but shouldn't be how you're building you JavaScript out.

您要求的是有道理的,但不应该是您构建 JavaScript 的方式。

Technically, there is a way of creating vars with names you build dynamically, but you shouldn't use it as it's slow, and if users are specifying what's in the array, it's unsafe and the feature is being needed in a couple of years, so your old stuff might break in future browsers.

从技术上讲,有一种方法可以使用动态构建的名称创建变量,但您不应该使用它,因为它很慢,而且如果用户指定数组中的内容,这是不安全的,并且在几年内需要该功能,所以你的旧东西可能会在未来的浏览器中损坏。

Meanwhile, you could easily do something like:

同时,您可以轻松地执行以下操作:

var obj = {},
    arr = [ "one", "two", "three" ],

    i = 0,
    len = arr.length,
    val = "",
    name = "";

for (; i < len; i += 1) {
    name = "item" + i;
    val = arr[i];
    obj[name] = val;
}

Now you can call obj.item1; // "two"

现在你可以打电话 obj.item1; // "two"

If you're really desperate, you can use windowas objso when you're writing stuff in the global scope, you can just write item0; // "one"but this really isn't a great idea, for several reasons (readability, maintainability, likelihood of overwriting somebody else's properties, etc).

如果你真的很绝望,你可以使用windowas objso 当你在全局范围内写东西时,你可以直接写,item0; // "one"但这真的不是一个好主意,原因有几个(可读性、可维护性、覆盖其他人的可能性)属性等)。

回答by bukart

If you really want the variable named so, here's a solution

如果你真的想要这样命名的变量,这里有一个解决方案

function fooBar(value) {
    this.value = value;
}

var arr = new Array(
    "some value",
    "some other value",
    "a third value"
);

(function(context) {
    for ( var i = 0; i < arr.length; i++) {
       var key = 'object' + ( i + 1 );
       this[ key ] = new fooBar( arr[ i ] );
     }
}(window));

alert(object1.value);
alert(object2.value);
alert(object3.value);

If you don't want global variables object1... just replace the keyword windowwith thisand it will produce local variable to the current scope.

如果您不想要全局变量object1……只需将关键字替换为windowwith this,它就会为当前作用域生成局部变量。

Test it out here: http://jsfiddle.net/bukart/F8ham/1/

在这里测试一下:http: //jsfiddle.net/bukart/F8ham/1/