如何在循环中更新对象属性

如何在循环中更新对象属性

本文介绍了如何在循环中更新对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个我在尝试使用循环时没想到的行为,以便更改对象中属性的值集。

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/

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']);
    });

});

我希望得到1 2 3 4作为存储在每个对象中的值,但是,我得到的是什么是4 4 4 4,这对我来说没有意义。

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.

任何关于这种行为的提示都非常受欢迎,谢谢

Any hint on this behavior is more than welcome, thanks

推荐答案

当你的代码调用 .push()并传递 my_object ,传递的是对象的引用。没有复制。

When your code calls .push() and passes my_object, what's being passed is a reference to the object. No copy is made.

因此,您已将对完全相同的对象的四个引用推送到数组中。

Thus, you've pushed four references to the exact same object into the array.

JavaScript对象总是以引用的形式参与表达式。没有其他方法可以处理对象。因此,当您创建变量并将其值设置为对象时,您实际上将其值设置为对象的引用。与参数传递相同,以及对象可以出现在表达式中的任何其他位置。

JavaScript objects always participate in expressions in the form of references. 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.

在这种情况下,您可以非常轻松地创建新对象;只需省去 my_object 并在每次迭代时推送一个新的:

In this case, you can create new objects pretty easily; just dispense with my_object and push a fresh one on each iteration:

    object_container.push( { value: value } );

这篇关于如何在循环中更新对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 00:30