简体   繁体   English

如何在循环内更新对象属性?

[英]How to update object properties within a loop?

I have found a behavior I did not expect when trying to use a loop in order to change the value set for a property in an object. 我发现尝试使用循环以更改对象中属性的值设置时没有想到的行为。

Basically, I declare my object outside the loop. 基本上,我在循环外声明我的对象。 Then I loop on an array of numeric values, which values are used to update the object property. 然后,我遍历一个数值数组,这些值用于更新对象属性。 Inside the loop, I store the current object state inside an external array. 在循环内部,我将当前对象状态存储在外部数组中。

The result is that instead of having an array containing a series of objects with different numeric values, I end up having the same numeric values in each object stored. 结果是,我没有在数组中包含一系列具有不同数值的对象,而是最终在每个存储的对象中使用了相同的数值。

Here is the fiddle http://jsfiddle.net/fAypL/1/ 这是小提琴http://jsfiddle.net/fAypL/1/

jQuery(function(){

    var object_container = [];

    var numeric_values = [1, 2 , 3, 4];

    var my_object = {};


    jQuery.each(numeric_values, function(index, value){
        my_object['value'] = value;
        object_container.push(my_object);
    });

    jQuery.each(object_container, function(index, value){
        jQuery('#content').prepend(value['value']);
    });

});

I would expect to get 1 2 3 4 as values stored in each object, however, what I get is 4 4 4 4, which does not make sense to me. 我希望得到1 2 3 4作为存储在每个对象中的值,但是,我得到的是4 4 4 4,这对我来说没有意义。

Any hint on this behavior is more than welcome, thanks 关于这种行为的任何提示都值得欢迎,谢谢

When your code calls .push() and passes my_object , what's being passed is a reference to the object. 当您的代码调用.push()并传递my_object ,传递的是对该对象的引用 No copy is made. 没有副本。

Thus, you've pushed four references to the exact same object into the array. 因此,您已将对完全相同的对象的四个引用推入数组。

JavaScript objects always participate in expressions in the form of references. JavaScript对象始终以引用的形式参与表达式。 There's no other way to deal with objects. 没有其他方法可以处理对象。 Thus when you create a variable, and set its value to be an object, you're really setting its value to be a reference to the object. 因此,当您创建变量并将其值设置为对象时,实际上是将其值设置为对该对象的引用。 Same with parameter passing, and anywhere else an object can appear in an expression. 与参数传递相同,其他任何对象都可以出现在表达式中。

In this case, you can create new objects pretty easily; 在这种情况下,您可以轻松创建新对象。 just dispense with my_object and push a fresh one on each iteration: 只需放弃my_object并在每次迭代中推送一个新的:

    object_container.push( { value: value } );

You are not creating a new object each time around the loop - you are just updating the same existing object and pushing references of that to the object array. 您并不是在每次循环时都创建一个新对象-您只是在更新相同的现有对象并将该对象的引用推送到对象数组。 To create a new object you want to do something like: 要创建一个新对象,您需要执行以下操作:

my_object = { 'value': value };
object_container.push(my_object);

In this case you now will get something more like what you were looking for. 在这种情况下,您现在将获得更像您所寻找的东西。 See the updated fiddle here: http://jsfiddle.net/fAypL/2/ . 在此处查看更新的小提琴: http : //jsfiddle.net/fAypL/2/

Best of luck! 祝你好运!

One more thought (Clone!) - If you are really tied to using the same object each time, just clone the object before you add to the array. 再想一想(克隆!) -如果您确实确实每次都使用同一对象,那么只需在添加到数组之前克隆该对象即可。 There is a great solution for that here . 有一个很好的解决方案,在这里

You are using jQuery so if what you want is to merge without effecting the original look at : 您正在使用jQuery,因此,如果要合并而不影响原始外观:

var both_obj = $.extend( {}, default_obj , adding_obj );

This will leave your original object changed, also good to use for a copy . 这将保留原始对象的更改,也可以很好地用于copy

jquery docs - extend() jQuery文档-extend()

An alternate version is to use an object with a constructor and the new keyword: 另一种版本是使用带有构造函数和new关键字的对象:

var object_container = [];  
var numeric_values = [1, 2 , 3, 4]; 

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


jQuery.each(numeric_values, function(index, value){     
    object_container.push(new MyObject(value));
});

jQuery.each(object_container, function(index, value){
    jQuery('#content').prepend(value['value']);
});

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM