Wechat 如何在微信小节目中使用变量作为索引';设置数据功能?

Wechat 如何在微信小节目中使用变量作为索引';设置数据功能?,wechat,Wechat,我喜欢使用listenSwiper来捕获在swiper模块中进行的滑动,从而更改当前项目样式的上一个和下一个项目 listenSwiper: function(e) { var prev = 'items['+(e.detail.current-1)+'].x' var now = 'items['+(e.detail.current)+'].x' var next = 'items['+(e.detail.current+1)+'].x' console.l

我喜欢使用listenSwiper来捕获在swiper模块中进行的滑动,从而更改当前项目样式的上一个和下一个项目

  listenSwiper: function(e) {
    var prev = 'items['+(e.detail.current-1)+'].x'
    var now = 'items['+(e.detail.current)+'].x'
    var next = 'items['+(e.detail.current+1)+'].x'
    console.log(prev)
    console.log(now)
    console.log(next)
    this.setData({
      prev:12,
      now:0,
      next:-12,
    })
  },
问题不是将
prev
now
next
识别为变量,而是将它们作为字符串处理,这意味着它在现有数组中添加了三个新键,而不是修改数组:

this.setData({
  'items[0].x':12,
  'items[1].x':0,
  'items[2].x':-12,
})

在ES5或更早版本中,不能在对象文本中使用变量作为属性名。您唯一的选择是执行以下操作:

var data = {};
data[prev] = 12;
data[now] = 0;
data[next] = -12;
在ES6中,您可以使用。您可以这样做:

this.setData({
  [prev]: 12,
  [now]: 0,
  [next]: -12
})
类似问题: