我有以下代码:
$scope.fetching = [];
$scope.loading = [];
$scope.fetching.start = function (activity) {
var index = this.indexOf(activity);
if (index == 0)
this.push(activity)
};
$scope.fetching.success = function (activity) {
var index = this.indexOf(activity);
if (index >= 0)
this.splice(index, 1);
};
$scope.loading.start = function (activity) {
var index = this.indexOf(activity);
if (index == 0)
this.push(activity)
};
$scope.loading.success = function (activity) {
var index = this.indexOf(activity);
if (index >= 0)
this.splice(index, 1);
};
我在一个数组中存储正在加载的所有内容的列表,在另一个数组中存储正在获取的所有内容的列表。为了使用这些,我编写了如下代码:
$scope.fetching.start("Fetching new topics");
$scope.fetching.success("Fetching new topics");
$scope.loading.start("Loading new ideas");
$scope.loading.success("Loading new ideas");
有没有一种方法可以让我不必重复使用完全相同的代码来获取和加载数组?
最佳答案
由于您的数组/对象具有相同的结构,因此您可以编写一个函数来构建该类型的对象。
function buildModifiedArray() {
var arr = [];
arr.start = function (activity) {
var index = this.indexOf(activity);
if (index == 0)
this.push(activity)
};
arr.success = function (activity) {
var index = this.indexOf(activity);
if (index >= 0)
this.splice(index, 1);
};
return arr;
}
$scope.fetching = buildModifiedArray();
$scope.loading = buildModifiedArray();
关于javascript - 有没有一种方法可以组合函数并将它们添加到 Javascript 中的多个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20351492/