小程序this.setData修改对象、数组中的值

发布时间:2024年01月08日

在微信小程序的前端开发中,使用this.setData方法修改data中的值,其格式为
this.setData({ ‘参数名1’: 值1,‘参数名2’: 值2)}
注意:如果是简单变量,参数名可以不加引号。

下面提供2种方式对data中的对象、数组中的数据进行修改:
假设原数据为:

data: {
    userInfo: {
      username: 'little',
      sex: 'female'
    },
    arr: [1,2,3,4,5,6],
},

方式一:使用[‘字符串’]

this.setData({
  // 写法一:
  ['userInfo.username']: 'plum',
  ['arr[2]']: 10
 // 写法二:
 'userInfo.username': 'plum',
 'arr[2]': 10,
})

当字符串中含有变量时,使用arr[${index}],并且外层的[]不可省略
this.setData({ [cars[${index}]]: 20})

方式二: 构造变量,重新赋值

  var temp = this.data.userInfo
  temp.username = 'plum'
  this.setData({userInfo: temp})

  var temp = this.data.arr
  temp[2] = 10
  this.setData({arr: temp})

另需注意:数组不可直接在xml中使用,要么遍历要么转为字符串后在xml中展示。

文章来源:https://blog.csdn.net/qq_45290368/article/details/135450944
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。