微信小程序 数组动态添加方式

【默认初始状态】

Page({
  data: {
    temparr:[
      {
        text:'标题一'
      },
      {
        text: '标题二'
      }
    ]
  },
  onLoad:function(){

  }
})
<view>
  <text>这个会覆盖原有的数据</text>
</view>
<view wx:for="{{temparr}}" wx:for-item="item" wx:for-index="index">
  <text>序号:{{index+1}},</text>
  <text>文本:{{item.text}}</text>
</view>

【如下方式赋值无效】

    var that=this;
    var datalist =[
      {
        text:'标题三'
      },
      {
        text: '标题四'
      },
      {
        text: '标题五'
      }
    ];

    that.data.temparr = datalist;

【覆盖原有数据的方式一】

Page({
  data: {
    temparr:[
      {
        text:'标题一'
      },
      {
        text: '标题二'
      }
    ]
  },
  onLoad:function(){

    var that=this;
    var datalist =[
      {
        text:'标题三'
      },
      {
        text: '标题四'
      },
      {
        text: '标题五'
      }
    ];

    //覆盖之前的数据 - 写法一
    const _temparr = {};
    datalist.forEach(function (item, index) {
      _temparr[`temparr[${index}].text`] = item.text
    });
    that.setData(_temparr);
  }
})
<view>
  <text>这个会覆盖原有的数据</text>
</view>
<view wx:for="{{temparr}}" wx:for-item="item" wx:for-index="index">
  <text>序号:{{index+1}},</text>
  <text>文本:{{item.text}}</text>
</view>

【覆盖原有数据方式二】

Page({
  data: {
    temparr:[
      {
        text:'标题一'
      },
      {
        text: '标题二'
      }
    ]
  },
  onLoad:function(){

    var that=this;
    var datalist =[
      {
        text:'标题三',
        name:'a'
      },
      {
        text: '标题四',
        name: 'b'
      },
      {
        text: '标题五',
        name: 'c'
      }
    ];

    that.setData({
      temparr: datalist
    });
  }
})
<view>
  <text>这个会覆盖原有的数据</text>
</view>
<view wx:for="{{temparr}}" wx:for-item="item" wx:for-index="index">
  <text>序号:{{index+1}},</text>
  <text>文本:{{item.text}}</text>
</view>

【原有数据上叠加】

Page({
  data: {
    temparr:[
      {
        text:'标题一'
      },
      {
        text: '标题二'
      }
    ]
  },
  onLoad:function(){

    var that=this;
    var datalist =[
      {
        text:'标题三',
        name:'a'
      },
      {
        text: '标题四',
        name: 'b'
      },
      {
        text: '标题五',
        name: 'c'
      }
    ];

    //叠加数据
    const length=that.data.temparr.length;
    datalist.forEach(function (item, index) {
      that.data.temparr.push({ text: item.text });
    });
    that.setData({
      temparr: that.data.temparr
    });
  }
})
<!--index.wxml-->
<view>
  <text>原有的数据上叠加</text>
</view>
<view wx:for="{{temparr}}" wx:for-item="item" wx:for-index="index">
  <text>序号:{{index+1}},</text>
  <text>文本:{{item.text}}</text>
</view>


版权声明:本文为lmy_520原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。