【问题标题】:Splicing one array with another array values将一个数组与另一个数组值拼接
【发布时间】:2017-03-11 04:00:02
【问题描述】:

我有一个函数displaySelectedRole(),我有变量$scope.Role$scope.rolenames。我需要从$scope.rolename. 中删除$scope.role 中的所有可用值

$scope.role= ["A","B","C"]; 

$scope.rolename =["A","B","C","D","E"]

我需要拼接值得到$scope.rolename = ["D","E"]

$scope.displaySelectedRole = function(role, index) {
           debugger;
           $scope.role.splice(RoleNames[index]);
            console.log($scope.role);

我尝试使用基于 index 的拼接,但问题是它在控制台中给出了空数组值。

【问题讨论】:

  • $scope.rolename.filter(x=>!$scope.role.includes(x))

标签: javascript angularjs arrays splice


【解决方案1】:

您可以使用filter

var $scope = {};  // Ignore this line
$scope.role= ["A","B","C"]; 
$scope.rolename = ["A","B","C","D","E"];

$scope.rolename = $scope.rolename.filter(function(role){
   return $scope.role.indexOf(role) === -1;
})

console.log($scope.rolename);

如果您想直接删除它们,您可以遍历 $scope.role 并使用拼接

   var $scope = {};  // Ignore this line
   $scope.role= ["A","B","C"]; 
   $scope.rolename = ["A","B","C","D","E"];

   $scope.role.forEach(function(role){
   var index = $scope.rolename.indexOf(role);
   if(index !== -1) $scope.rolename.splice(index, 1);
})

console.log($scope.rolename);

注意:Array.filter 会返回一个新数组,而array.splice 会修改原始数组。

参考

【讨论】:

    【解决方案2】:

    你可以Underscore.js's difference(),它的目的是减少数组:

    $scope.role = ["A","B","C"]; 
    $scope.rolename = ["A","B","C","D","E"];
    $scope.diff = _.difference($scope.rolename, $scope.role); // ["D","E"]
    

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多