javascript - 有没有一种方法可以组合函数并将它们添加到 Javascript 中的多个数组中?

标签 javascript

我有以下代码:

$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/

相关文章:

javascript - 如何在自己的函数内部调用该函数

javascript - javascript 和 plsql 任务之间动态操作的交互

javascript - 在 for 循环中合并 $http.get JSON 数据

javascript - AngularJS - 表单提交

javascript - Jquery If, Else slider

javascript - 响应式 Javascript/jQuery 图片库

javascript - 在组件中生成随机值时的 Next.js/React 警告

javascript - 变量内部循环内部成功 : in ajax call JS

javascript - 我的 javascript 函数逻辑有什么问题?

javascript - 如何使用 Javascript 格式化变量的值?