javascript - The value obtained when looping in angular is the last value
天蓬老师
天蓬老师 2017-07-05 11:05:07
0
2
836

code show as below:

angular.forEach(data.body.data.assets,function(val,ind){

                    angular.forEach(val.userAssetList,function(data,index){
                        val.userDtoName = data;
                        // alert(data.userDTO);
                        if(val.assetCount != val.availableCount){
                            lay.push(val);
                        }
                    })
                   })
          最后我的lay数组中userDtoName的值全部都是最后一个data的值。为什么。但是每一个循环中alert出来的是不同的。
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
曾经蜡笔没有小新

val is an object, equivalent to a pointer, so the same object is pushed in every time

Since I don’t know what other attributes and functions your val has, here is only an alternative: push({...val, userDtoName: data})

Using ES6’s... spread operator.

洪涛

If you read it correctly, what you use conveniently is val.userAssetList, but you put val into lay. It’s the same every time, and you always execute lay.push(val)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template