将一个数组与另一个数组值拼接
Splicing one array with another array values
我有一个函数 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);
我尝试使用基于索引的拼接,但问题是它在控制台中给出了空数组值。
你可以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"]
您可以使用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
并使用 splice
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
将 return 一个新数组,不像 array.splice
会修改原始数组。
参考
我有一个函数 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);
我尝试使用基于索引的拼接,但问题是它在控制台中给出了空数组值。
你可以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"]
您可以使用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
并使用 splice
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
将 return 一个新数组,不像 array.splice
会修改原始数组。