首页 > Angularjs 函数里怎么把函数中变量名做为一个形参传入并使用?

Angularjs 函数里怎么把函数中变量名做为一个形参传入并使用?

问题是这样的,有一个function长这样:

$scope.isExist = function (id) {
    return $scope.physical.map(function (type) {
        return type.id;
    }).indexOf(id);
};

代码里有n个这样的函数,除了第二行的 $scope.physical 不一样外,其它都一样。

问题:如何优化成一个函数,把第二行中的变量做为参数传入进来,这样代码能简洁不少,谢谢。


不太懂你的疑问,你已经给出方案了啊,这样?

javascript$scope.isExist = function (id, name) {
    return $scope[name].map(function (type) {
        return type.id;
    }).indexOf(id);
};

http://underscorejs.org/#findIndex


$scope.isExist = function (array, key, value) {
    return array.map(function (item) {
        return item[key];
    }).indexOf(value);
};
【热门文章】
【热门文章】