Javascript Firefox和IE中的For循环错误,但不包括Chrome

Javascript Firefox和IE中的For循环错误,但不包括Chrome,javascript,google-chrome,internet-explorer,firefox,runtime-error,Javascript,Google Chrome,Internet Explorer,Firefox,Runtime Error,我有一个奇怪的问题:我在JavaScript中有一个for循环,它在Chrome中完全按照预期工作,但在Firefox或IE中却没有。在Firefox和IE中,它向数组中添加了一个未定义的项,我不知道为什么 angular.module('app', []) .controller('itemCtrl', function($scope){ $scope.itemsa = [ { name: 'testa' }, { name: 'testb' }

我有一个奇怪的问题:我在JavaScript中有一个for循环,它在Chrome中完全按照预期工作,但在Firefox或IE中却没有。在Firefox和IE中,它向数组中添加了一个未定义的项,我不知道为什么

angular.module('app', [])

.controller('itemCtrl', function($scope){
    $scope.itemsa = [
        { name: 'testa' },
        { name: 'testb' }
    ];
    $scope.itemsb = [];

    $scope.doSomething = function(IDparam) {
        for(var i = 0; i < $scope.itemsb.length; i++){
            if ($scope.itemsb[i].name === $scope.itemsa[IDparam].name) { ... }; };
angular.module('app',[])
.controller('itemCtrl',函数($scope){
$scope.itemsa=[
{name:'testa'},
{name:'testb'}
];
$scope.itemsb=[];
$scope.doSomething=函数(IDparam){
对于(变量i=0;i<$scope.itemsb.length;i++){
如果($scope.itemsb[i].name==$scope.itemsa[IDparam].name){…};};
根据两种浏览器中的开发人员工具,
$scope.itemb
在for循环开始行
for(var i=0;i<$scope.itemsb.length;i++)
中的长度为0,但(无论出于何种原因)它仍然会启动for循环(据我所知,它不应该启动for循环),然后在下面的行
if($scope.itemsb[i].name==$scope.itemsa[IDparam].name)
突然出现了0数组位置的未定义项(当然会产生错误)


有什么想法吗?

错误可能会出现在您调用
$scope.doSomething
的地方,或者您正在向
$scope.itemsb
添加值的地方。您能分享这两个部分的代码吗?谢谢。感谢您的快速回答!在同一个控制器中调用
$scope.doSomething
。这是唯一可以
itemsb数组
已更改:
$scope.addItemb=function(IDparam){if($scope.doSomething(IDparam)){return false;}else{$scope.$apply($scope.itemb.push($scope.itema[IDparam]);return true;};}
我看到你提到了
itema
itemb
。这些不应该是
itemsa
itemsb
吗?还有一些其他的东西。我强烈建议使用Firefox的开发工具来浏览这些代码。他们有一种方法可以在代码中设置断点。我会在循环中设置它,并增加调用堆栈你能找到为什么
$scope.itemsb
会被填充。啊,对不起,你是对的。我在调整这里的代码时犯了这些错误。它在实际代码中是正确的(如果不是,它在Chrome中就不能正常工作)。