微信小程序中JS对象属性赋值

 在JS代码中为了让数据带有指定的键传入前端,必须修改setData内通过变量传进来的key指定。

原来的源代码:

porcessDoubanData: function (moviesDouban) {
var movies = [];
for ( var idx in moviesDouban.subjects) {
var subject = moviesDouban.subjects[idx];
var title = subject.title;
if (title.length >= 6) {
title = title.substring( 0.6) + "...";
}
var temp = {
title: title,
average: subject.rating.average,
coverageUrl: subject.images.large,
movieId: subject.id
}
movies.push(temp)
}
 this.setData({
 movies:movies
})
}
需要将movies修改为添加进来的参数settedKey来改变

修改后代码
porcessDoubanData: function (moviesDouban, settedKey) {
var movies = [];
for ( var idx in moviesDouban.subjects) {
var subject = moviesDouban.subjects[idx];
var title = subject.title;
if (title.length >= 6) {
title = title.substring( 0.6) + "...";
}
var temp = {
title: title,
average: subject.rating.average,
coverageUrl: subject.images.large,
movieId: subject.id
}
movies.push(temp)
}
var readyData = {};
readyData[settedKey] = movies;
this.setData(readyData);
}
})

1.定义了变量readyData ={}空的Javascript对象
2.readyDate[settedKey] = moives;对属性进行赋值
3.this.setData(readyData);即可

本身是很简单的JS对象属性赋值,设定了readyData对象赋值属性即可,但是其本质利用了JS动态语言的特性。
能体现出本身我对JS语言掌握不是很牢固,利用动态特性可以对代码进行更好的编写。

你可能感兴趣的:(前段_微信小程序)