gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:02:59 24 4
gpt4 key购买 nike

我有以下代码:

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com