2014-10-06 54 views
0

我需要根據if語句的結果向數組添加錯誤消息。下面的代碼僅在我輸入應觸發兩者的數據時纔會返回第二條錯誤消息。我知道.push()不只是添加到前一個數組,而是他們必須解決的唯一方法是創建一個for循環。我覺得有一些簡單的功能在某處,我只是想念。根據if語句添加到Javascript數組

$scope.error = {}; 
    if ($password == null || $vPassword == null || $email == null || $vEmail == null) { 
     console.log('All fields must be filled in'); 
    } else { 
     if ($scope.verifyPassword !== $scope.password) { 
      $scope.error[scope.error.length()] = 'Your passwords must match...'; 
     } 
     if ($scope.verifyEmail !== $scope.email) { 
      $scope.error.push = ['Your email addresses must match...']; 
     } 
     console.log($scope.error); 
    } 

我認爲這個代碼很好理解。讓我知道你是否需要更多信息。

謝謝!

編輯:我不知道什麼代碼產生了我解釋的錯誤。抱歉。上面的代碼是糟糕的代碼,我試圖讓它工作。很顯然,其中大部分都沒有意義。被接受的答案是我原本認爲會產生這個錯誤,但顯然它起作用。對不起,這個蹩腳的帖子。

+0

對於數組:'$ scope.error = []';那麼只需'.push(「字符串」)'根據需要 – 2014-10-06 16:12:19

回答

3

push是一個函數,應該使用()來調用。

$scope.error.push('Your email addresses must match...'); 

此外,您不能在不是Array的對象上調用push。你必須初始化$scope.error作爲Array

$scope.error = []; 
+0

我不像我的問題一樣愚蠢讓我看起來。閱讀我編輯的問題。雖然謝謝!有用! – 2014-10-06 16:22:14

0

您需要更改$scope.error到一個數組,而不是一個對象,然後將.push()適當工作。

$scope.error = []; 
$scope.error.push("Your passwords must match..."); 

console.log($scope.error); 

可生產

["Your passwords must match..."]