2015-04-23 50 views
5

我有这样的功能:条件语句来检查,如果数组是空的,角JS

$scope.doPaste = function(destination) {        
    if ($scope.selectCopy.ids != []) { 
     console.log("will copy"); 
     $scope.CopyFiles(destination); 
    } 
    if ($scope.selectMove.ids != []) { 
     console.log("will move"); 
     $scope.MoveFiles(destination); 
    }         
}; 

在我的应用程序,$scope.selectMove.ids$scope.selectCopy.ids不能同时非空。我的意思是,例如当$scope.selectMove.ids非空时$scope.selectCopy.ids为空。

我的问题是,在控制台中,我总是看到两者都会复制并移动。

+3

你最好检查'.length'属性! –

回答

9

注意[] != []回报true(因为它们是不同的对象)。您应该使用length检查数组是否为空。

if($scope.selectCopy.ids.length > 0){ 
    console.log("will copy"); 
    $scope.CopyFiles(destination); 
} 
+0

这是一个很好的参考什么和不解决为真:http://www.quirksmode.org/js/boolean.html – MBielski

+1

谢谢,它的作品 – Yuri

+0

@marwa不客气。 – xdazz

3

您必须检查空值或未定义的值。

$scope.doPaste=function(destination) { 
    if ($scope.selectCopy.ids && $scope.selectCopy.ids.length > 0) { 
     console.log("will copy"); 
     $scope.CopyFiles(destination); 
    } 
    if ($scope.selectMove.ids && $scope.selectMove.ids.length > 0) { 
     console.log("will move"); 
     $scope.MoveFiles(destination); 
    }        
}; 
+0

谢谢,它的工作 – Yuri

6

我想你应该检查angular.isObject()如果它是一个对象,它会返回true。

$scope.doPaste = function(destination) { 
    if (angular.isObject($scope.selectCopy.ids) && $scope.selectCopy.ids.length > 0) { 
     console.log("will copy"); 
     $scope.CopyFiles(destination); 
    } 

    if (angular.isObject($scope.selectMove.ids) && $scope.selectMove.ids.length > 0){ 
     console.log("will move"); 
     $scope.MoveFiles(destination); 
    }        
}; 
+1

@downvoter为什么downvote? –

+1

是的,这个解决方案应该可以正常工作。 –

0

如果你想确保它与体内的至少一个元素的数组,做一个小功能检查。 (也许你会想以后延长该检查)

var isNonEmptyArray = function(ar){ 
    return Array.isArray(ar) && (ar.length > 0); 
}; 

$scope.doPaste=function(destination){ 

    if(isNonEmptyArray($scope.selectCopy.ids)){ 
    console.log("will copy"); 
    $scope.CopyFiles(destination); 
    } 
    if(isNonEmptyArray($scope.selectMove.ids)){ 
    console.log("will move"); 
    $scope.MoveFiles(destination); 
    } 
}; 

也避免弱!=操作,使用严格的一个!==

[]比较没有帮助,[]会一直返回一个新的数组。

2

可能是你需要使用if else条件:

if (empty){ 
    console.log('empty'); 
}else{ 
    console.log('not empty'); 
} 

在你的代码。它是这样的一些:

$scope.doPaste=function(destination) { 
    if ($scope.selectCopy.ids && $scope.selectCopy.ids.length > 0) { 
     console.log("will copy"); 
     $scope.CopyFiles(destination); 
    } 
else { 
     console.log("will move"); 
     $scope.MoveFiles(destination); 
    }        
};