2015-04-23 114 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); 
    }        
};