Angular JS - Array.splice() 导致未定义的项目
Angular JS - Array.splice() causes undefined items
美好的一天!
我目前正在通过使用 push 方法在索引 0 处添加对象并使用 splice 方法删除项目来操作我的数组。正如我所阅读和理解的那样,当您从数组中拼接一个项目时,它不会留下带有 'undefined' 项目的数组。问题是,我目前在使用拼接时得到一个 'undefined' 项目。
这是我添加条目的代码:
addOrRemoveRating(0,0,{
rating : 0,
tran_number : transaction_number,
email : $scope.called_numbers[0].email
});
这是我删除条目的代码:
addOrRemoveRating(array_index,1);
其中 array_index 是现有索引。
最后一部分是拼接发生的地方:
addOrRemoveRating = function(index, item, object){
$scope.temp_called_numbers.splice(index, item, object);
}
例如,我的数组中有 3 个对象 - [Object, Object, Object],删除项目后,它 returns - [Object, Object, undefined]。
我的代码有什么遗漏或错误吗?非常感谢任何帮助、参考或指导。
当您仅使用两个参数调用函数时,object
将是 undefined
,因此,undefined
将添加到数组中。
试试这个
$scope.temp_called_numbers.splice.apply($scope.temp_called_numbers, arguments);
使用它,您可以利用 Array.prototype.splice
的可变参数特性,并传递多个对象以添加到数组中。
这不是 AngularJS 问题,严格来说是 Javascript。带三个参数调用splice()
会在指定位置拼接第三个参数。如果您省略第三个参数 (object
),它只会从数组中删除对象。
addOrRemoveRating = function(index, item, object){
if (object)
$scope.temp_called_numbers.splice(index, item, object);
else
$scope.temp_called_numbers.splice(index, item);
}
美好的一天!
我目前正在通过使用 push 方法在索引 0 处添加对象并使用 splice 方法删除项目来操作我的数组。正如我所阅读和理解的那样,当您从数组中拼接一个项目时,它不会留下带有 'undefined' 项目的数组。问题是,我目前在使用拼接时得到一个 'undefined' 项目。
这是我添加条目的代码:
addOrRemoveRating(0,0,{
rating : 0,
tran_number : transaction_number,
email : $scope.called_numbers[0].email
});
这是我删除条目的代码:
addOrRemoveRating(array_index,1);
其中 array_index 是现有索引。
最后一部分是拼接发生的地方:
addOrRemoveRating = function(index, item, object){
$scope.temp_called_numbers.splice(index, item, object);
}
例如,我的数组中有 3 个对象 - [Object, Object, Object],删除项目后,它 returns - [Object, Object, undefined]。
我的代码有什么遗漏或错误吗?非常感谢任何帮助、参考或指导。
当您仅使用两个参数调用函数时,object
将是 undefined
,因此,undefined
将添加到数组中。
试试这个
$scope.temp_called_numbers.splice.apply($scope.temp_called_numbers, arguments);
使用它,您可以利用 Array.prototype.splice
的可变参数特性,并传递多个对象以添加到数组中。
这不是 AngularJS 问题,严格来说是 Javascript。带三个参数调用splice()
会在指定位置拼接第三个参数。如果您省略第三个参数 (object
),它只会从数组中删除对象。
addOrRemoveRating = function(index, item, object){
if (object)
$scope.temp_called_numbers.splice(index, item, object);
else
$scope.temp_called_numbers.splice(index, item);
}