在做小程序開發時,需要將一個對象push到數組中,第一次寫法是
for(var j in that.data.goods ){//遍歷商品信息 獲取商品id // console.log(that.data.goods[j].id) for(var h in that.data.cart.list){//遍歷緩存中購物車列表,獲取下標 if(j==h){ // var goods_id_list ={'id':'','num':''};//定義一個接受對象 console.log(that.data.goods[j].id)//獲取了所選商品的id值 console.log(that.data.cart.list[h])//獲取了所選商品的數量 that.data.cartGoods=that.data.goods[j].id; that.data.cartGoods = that.data.cart.list[h]; // var aa = that.data.cartGoods goods.push(that.data.cartGoods);//添加數組信息 } }
這樣輸出的結果你數組元素都是最后一個對象。因為tmp聲明在for循環之外,當listData數組push這個tmp對象時,一直是同一個對象,而並不是將對象的數據壓入,只是在listData數組建立了一個對象的引用關系。故隨着for的i值改變,tmp對象內部的內容也跟着改變,而listData壓入的對象卻始終是tmp這個對象(tmp生命周期不受for循環影響)。所以最終console.log(listData)出來的對象數組里面的元素都是一樣的數據。簡言之:就是tmp對象的數據再變,但是listData壓入的tmp卻是不變的。
需要在里面定義一個接受數組
for(var j in that.data.goods ){//遍歷商品信息 獲取商品id // console.log(that.data.goods[j].id) for(var h in that.data.cart.list){//遍歷緩存中購物車列表,獲取下標 if(j==h){ var goods_id_list ={'id':'','num':''};//定義一個接受對象 console.log(that.data.goods[j].id)//獲取了所選商品的id值 console.log(that.data.cart.list[h])//獲取了所選商品的數量 goods_id_list.id=that.data.goods[j].id; goods_id_list.num = that.data.cart.list[h]; // var aa = that.data.cartGoods goods.push(goods_id_list);//添加數組信息 } } }