search

Home  >  Q&A  >  body text

javascript - The value obtained when looping in angular is the last value

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出来的是不同的。
天蓬老师天蓬老师2709 days ago822

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 11:07:07

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 11:07:07

    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)

    reply
    0
  • Cancelreply