为什么Javascript对象没有改变?

时间:2017-02-09 15:20:52

标签: javascript angularjs

有人能解释我这种奇怪的js行为吗?

所有这些都在AngularJS中。

我在我的主app.js中有辅助函数,只需通过其id从数组中返回元素:

var MyLib = MyLib || {};

MyLib.helpers = {
    find: function(needle, stack) {
        for (var i = 0; i < stack.length; i++) {
            if(stack[i]._id === needle)
                return stack[i];
        }
        return false;
    }
}

然后我有工厂和功能来处理数据库更改:

// categories are grabbed from db
var categories = [some array of objects];


// change is object returned from database that has all info about object as well as new object itself
function handleChange(change) {
    var _category = MyLib.helpers.find(change.id, categories);

    // if deleted, that part is ok
    if(change.deleted) {
        var idx = categories.indexOf(_category);
        if(idx !== -1) {
            categories.splice(idx, 1);
        }
    } else {
        // if updated that part is weird
        if(_category) {
            _category = change.doc;
        }
        // if newly added that part is ok
        else {
            categories.push( angular.copy(change.doc) );
        }
    }
}

为什么当我尝试更新从类别数组中获取的元素时,不会在类别数组中更新?

// categories ARE NOT updated after this
_category = change.doc;

并且只有当我按照索引引用类别时才会这样:

// categories ARE updated after this although _category is returned from this array by index (find function)
var idx = categories.indexOf(_category);
categories[idx] = change.doc;

我不明白这一点......

2 个答案:

答案 0 :(得分:1)

您正在使用新值覆盖变量,并且对先前值的任何引用都将消失。

您可以使用angular.extend()

更新现有对象,而不是使用新对象覆盖原始对象值
angular.extend(_category, change.doc);

答案 1 :(得分:0)

我没有分析所有内容,但你应该总是有点符号。

_category按值传递,并且在&#39; MyLib.hel ...&#39;时不会更改已更改

var _category = MyLib.helpers.find(change.id, categories);

something.category通过引用传递,并且会在&#39; MyLib.hel ...&#39;时更改。已更改

var something.category = MyLib.helpers.find(change.id, categories);